Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

What are the keys differences between Comparable and Comparator.

and which is preferred over the other in what scenarios?

1 Answer

0 votes
by (7.2k points)

Comparator VS Comparable in JAVA

Comparator

1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price.              

2) Comparable affects the original class, i.e., the actual class is modified.                                                                                            

3) Comparable provides compareTo() method to sort elements.

4) Comparable is present in the java.lang package.

5) We can sort the list elements of Comparable type by the Collections.sort(List) method.

 

Comparable

  1. The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.

  2. Comparator doesn't affect the original class, i.e., the actual class is not modified.

  3. Comparator provides compare() method to sort elements.

  4. A Comparator is present in the java.util package.

  5. We can sort the list elements of Comparator type by Collections.sort(List,      Comparator) method.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 17, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...