What is the difference between comparable vs comparator in java?

Java provides two interfaces to sort objects using data members of the class: 

Using Comparable Interface

A comparable object can be compared with another object. The class itself must implement the java.lang.Comparable interface to compare its instances. Consider a movie category, whose members include rating, name, and year. Suppose we want to sort the list of movies by release year. We can use the Movie class to implement the Comparable interface and override the compareTo() method of the Comparable interface.

In Java, both "comparable" and "comparator" are interfaces used for sorting objects. However, they have different purposes and methods of implementation.

"Comparable" is an interface that defines a single method called "compareTo(Object obj)". This method is used to compare the current object with the object passed as a parameter. The "compareTo" method returns an integer value, indicating whether the current object is less than, equal to, or greater than the object passed as a parameter. This interface is useful when you want to sort objects based on their natural order, such as sorting a list of integers in ascending or descending order.

"Comparator", on the other hand, is an interface that defines two methods: "compare(Object obj1, Object obj2)" and "equals(Object obj)". The "compare" method is used to compare two objects and return an integer value, while the "equals" method is used to check whether two objects are equal. This interface is useful when you want to sort objects based on a custom order, such as sorting a list of strings in alphabetical order or a list of employees by their salary.

In summary, "comparable" is used to define a default ordering for objects, while "comparator" is used to define a custom ordering for objects.

Submit Your Programming Assignment Details