1. Introduction
Comparable interface is provided in java.lang
package. This interface is a part of Java Collections Framework. This interface imposes total ordering on the objects of the class which implements this interface. This ordering is referred to as the natural ordering. The Comparable
interface provides a method compareTo
which is referred as its natural comparison method.
Few classes which implement this interface are:
- BigDecimal
- BigInteger
- Date
- Double
- Integer
- Float
- Long
When a class implements this interface it means the class is defining how two objects of this class should be compared with each other. The result of the compareTo()
method tells whether the object is less than, equal or greater than the other object.
Classes which implement this interface can be automatically sorted by Collections.sort
and Arrays.sort
. Objects of the class which implement this interface can be used as keys in sorted map and as elements in sorted set without specifying a comparator.
2. Natural ordering consistency with equals()
It is recommended that the natural ordering of class should be consistent with equals but it is not required. The natural ordering of class is said to be consistent with equals() if and only if the result of obj1.compareTo(obj2)
is same as obj1.equals(obj2)
, where obj1 and obj2 are the objects of some class. When compared with null
, compareTo()
method should throw NullPointerException
. However, obj1.equals(null)
will return false
.
Let us discuss why this consistency is recommended. The purpose of equals()
method is to compare two objects and tell whether they are equal. And the purpose of compareTo()
is to compare two objects. compareTo()
should not only tell whether one object is less than or greater than the other but should also tell whether the objects are equal. If the comparison of equal objects is not consistent then the comparison operations may behave unreliably.
3. compareTo() method of Comparable interface
Comparable interface has only one method having following signature:
int compareTo(T o)
This method compares the object with the provided object. This method returns
- a negative integer if the object is less than the provided object.
- a positive integer if the object is greater than the provided object.
- zero, if the object is equal to the provided object.
The compareTo()
method should be transitive. It means, obj1.compareTo(obj2)>0
&& obj2.compareTo(obj3)>0
implies obj1.compareTo(obj3)>0
.
Comparable is used to compare objects of same type. For example, Comparable can be used to compare two Student class objects. It can not be used to compare Student and Employee class objects.
4. Example of Comparable
In this example, we’ll create a class Student
. This class will have two fields, rollNo
and totalMarks
to represent roll number and total marks obtained by a student. Our requirement is to compare total marks obtained by the student. If a student is having total marks greater than the other, we’ll consider the object greater than the other object.
package com.learnitweb; public class Student implements Comparable<Student> { private long rollNo; private int totalMarks; public Student(long rollNo, int totalMarks) { super(); this.rollNo = rollNo; this.totalMarks = totalMarks; } public long getRollNo() { return rollNo; } public void setRollNo(long rollNo) { this.rollNo = rollNo; } public int getTotalMarks() { return totalMarks; } public void setTotalMarks(int totalMarks) { this.totalMarks = totalMarks; } @Override public int compareTo(Student stu) { return this.totalMarks - stu.getTotalMarks(); } @Override public String toString() { return "Student [rollNo=" + rollNo + ", totalMarks=" + totalMarks + "]"; } }
package com.learnitweb; public class ComparableExample { public static void main(String args[]) throws InterruptedException { Student student1 = new Student(1, 450); Student student2 = new Student(2, 500); if (student1.compareTo(student2) < 0) { System.out.println("first object is less than the second object"); } else if (student1.compareTo(student2) > 0) { System.out.println("first object is greater than the second object"); } else if (student1.compareTo(student2) == 0) { System.out.println("both objects are equal"); } } }
Output
first object is less than the second object
5. Example of Comparable to sort ArrayList
We’ll use the Student
class of previous example. Since Student
class implements Comparable
, Collections.sort
can be used to sort a list of Student
objects.
package com.learnitweb; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortWithComparableExample { public static void main(String args[]) throws InterruptedException { Student student1 = new Student(1, 450); Student student2 = new Student(2, 500); Student student3 = new Student(2, 600); List<Student> list = new ArrayList(); list.add(student3); list.add(student2); list.add(student1); System.out.println("List before sort: " + list); Collections.sort(list); System.out.println("List after sort: " + list); } }