admin@onlinelearningcenter.in (+91) 7 999 01 02 03

Comparable and Comparator

Comparable and Comparator both are interfaces.

So to work with Comparable and Comparator the class should implements these two interfaces.

These two interfaces has some unimplemented methods. So when ever we are working with these interfaces we shouls implement these unimplemented methods.

Comparable: compareTo()

UseCase: Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. In this case We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface. 

Comparator: compare()

Comparator in Java compares two different class objects provided. 

UseCase: Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release, rating and name. In this case, we should write the Class to compare Movies by ratings,Class to compare Movies by name ,Class to compare Movies by year  and we override the method compare() of Comparator interface. 

NOTE:if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.

Published By : asvitha chunduru
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Comments

Jquery Comments Plugin