Difference between comparable and comparator in java

The Comparable interface is used to define the "natural order" of a class.The Comparable interface imposes the definition of the compareTo() method onto the class which is used during the sort process. 

It is true that some classes, such as the String and wrapper classes, have a natural order, but this is because they implement the Comparable interface and have a compareTo() method defined. Note that it is common to use these classes and methods when defining the sort criteria for other classes. 

The Comparator interface imposes the definition of a compare() method onto the implementing class. Similar to the Comparable interface, the compare() method is used during the sort process to arrange an array or collection of objects in the defined order. 

Both compareTo() and compare() return an int value (-1, 0, or 1), indicating to the sort process whether the two objects being compared should be exchanged or not. 

A class can implement each, although if more than two sort criteria are needed, it is common to implement the Comparator interface using a series of inner classes, perhaps anonymous. The Comparator interface can also be implemented by an external class on behalf of another class. Conversely, a class must implement its own Comparable interface to define its natural order. 

The advantage of the Comparable interface is that it's compareTo() method is used by default by a sort() method. With the Comparator interface, a reference to an object defining the particular compare() method to be used must be specified. 

Note that since version 1.5, generic versions of each interface are available, so the compareTo() and compare() parameters are defined in terms of the object types being sorted, not Object objects. 

Search:

Recent Posts