Back

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

I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?

1 Answer

0 votes
by (7.2k points)

Comparable in Java is an object to compare itself with another object. It helps to sort the list of custom objects. The java.lang.Comparable interface should be implemented by a class in order to compare its instances. 

Comparator in Java is an object for comparing different objects of different classes. Comparator interface in Java is also used to arrange the objects of user-defined classes. It includes two important comparator interface methods known as compare (Object obj1, Object obj2) and equals (Object element).

Implementing Comparable means "I can compare myself with another object." Implementing Comparator means "I can compare two other objects." 

Browse Categories

...