Comparable Interface

 The Comparable Interface is used to sort objects in Java. When a class implements Comparable, it means that the objects of that class can be ordered or compared with each other. There is only one method in this interface, which is called compareTo. It compares two objects and returns an integer value based on whether the current object is less than, equal to, or greater than the other object.

Here are some important things to know about the Comparable Interface:

  • It's used to decide the ordering of objects in a class.
  • It's meant for objects with natural ordering, which means the object itself must know how it is to be ordered.
  • Some important Wrapper Classes that implement this interface are Integer, Boolean, Byte, Character, Double, Float, Long, BigInteger, etc.
  • If a class implements the Comparable interface, then the collection of that object can be sorted automatically by using Collections.sort() or Arrays.sort() method, based on the natural order defined by the compareTo method.

There's also another way to sort objects, which is by using the Comparator Interface. If a class doesn't implement Comparable, then a separate class can be written that implements Comparator. Comparator is external to the element type being compared, and it's a separate class. We create multiple separate classes (that implement Comparator) to compare by different members. If sorting of objects needs to be based on natural order, then use Comparable. But if your sorting needs to be done on attributes of different objects, then use Comparator in Java.

Here's an example to understand better: Let's say we want to sort a class of students according to their roll numbers. This is a natural order, so we can use the Comparable interface. If we want to create Collections like PriorityQueue, TreeSet, TreeMap, etc. of this class, we don't need to do anything extra because the class is already Comparable. Here's how we can write the code:

java
class Student implements Comparable { String name; int rollNo; ........... // Comparing the current this object with the object s public int compareTo(Student s) { return (this.rollNo - s.rollNo); } ........... }

When two objects are compared, three possibilities arise:

  • A negative value is returned when the current object is smaller.
  • 0 is returned when both the objects are the same.
  • A positive value is returned when the current object is greater.

Using the sort() method, we can sort the students according to their natural order. We can also create a TreeMap, TreeSet, or any collection interface using increasing order or reverse order of sorting using sort(arr, Collections.reverseOrder()).

Previous Post Next Post