interface Comparator

interface Comparator


Comparator interface is from java.util package like other data structures. Some data structures TreeSet and TreeMap sort the elements in natural (ascending) order by default. The Comparator object is capable to change this order, the way customization requires. Programmer can get a precise control over ordering.

In Java, we come across a list of objects like all employees or all students etc. Many a times, it is required to sort them as the code demands. For example, a student may be required to sort by his roll number, name or marks etc.

To sort the objects, Java comes with two interfaces – java.lang.Comprable and java.util.Comparator. A class that requires sorting using these interfaces, should implement these interfaces and override the method. Now let us see Comparator interface and later Comparable interface with example code.

A interface Comparator object can compare two objects. The class using Comparator interface, should implement the interface and override the method compare().

The interface Comparator comes with two abstract methods and is a must to be overridden when the interface is implemented.

  1. int compare(Object obj1, Object obj2): Objects obj1 and obj2, under comparison, are passed as parameters. Returns an integer value depending on the objects under comparison.

    a) positive value – when obj1 is greater than obj2
    b) zero value – when obj1 equals obj2
    c) negative value – when obj1 is less than obj2

  2. boolean equals(Object obj): Returns true if both objects are same. Both objects should be comparators(that is , their classes should implement Comparator). This method also follows the general rules of equals()method. Generally, the programmer does not override this method and still program works as it is taken from Object class.

The comparator object is passed to Collections.sort() method to have a precise and complete control over sorting. Moreover, the Collections.reverseOrder() method returns an object of Comparator (illustrated in "Comparator Example").

A program, Comparator Example, is given where array list elements are sorted using Comparator interface.

Also for an in depth understanding, read Comparable vs. Comparator.

interface Comparator requires lot of practice to use it in development. Try it.

Leave a Reply

Your email address will not be published. Required fields are marked *