Wednesday, 18 November 2015

Difference between Comparable and Comparator

A class can implement the Comparable interface to define the natural ordering of the objects. If you take a list of Strings, generally it is ordered by alphabetical comparisons. So when a String class is created, it can be made to implement Comparable interface and override the compareTo method to provide the comparison definition. We can use them as,

str1.compareTo(str2);

Now, what will you do if you want to compare two strings based on it length. We go for the Comparator. We create a class and let it implement the Comparator interface and override compare method. We can use them as,

Collections.sort(listOfStrings, comparatorObj);

The natural ordering is up to the person designing the classes. Comparator can be used in that scenario also and it can be used when we need multiple sorting options. Imagine a situation where a class is already available and we cannot modify it. In that case also, Comparator is the choice.

No comments:

Post a Comment