Skip to main content

Posts

Showing posts with the label Comparable

What is the difference(or relation) between the Comparator and the Comparable interfaces?

Classes that implement these two interfaces play different roles in the sorting process. A class that implements the Comparable interface, i.e., a Comparable type, is the type that is sorted, while a class that implements the Comparator interface, i.e., a Comparator, is used to compare other types. A Comparable object can compare itself to another Object using its compareTo(Object other) method. The object itself defines how the comparison is done. Interface Comparable has a method: public int compareTo(T o) A Comparator object is used to compare two objects of the same type using the compare(Object other1, Object other2) method. When using a Comparator, the objects being compared don't need to define the rule of comparison. Interface Comparator has a method: public int compare(T o1, T o2)