We often need to compare two values in our Java programs. Comparing primitive values like int, char, float is very easy and can be done with comparison operators like <, >, == etc.
But comparing objects is a little different. For example, how would you compare two Employees? how would you compare two Students?
You need to explicitly define how the objects of user defined classes should be compared. For this purpose, Java provides two interfaces called Comparable and Comparator.
Once you define how the objects should be compared using any of these interfaces, you’ll be able to sort them using various library functions like Collections.sort or Arrays.sort.
Java Comparable interface intuition
By default, a user defined class is not comparable. That is, its objects can’t be compared. To make an object comparable, the class must implement the Comparable interface.
The Comparable interface has a single method called compareTo() that you need to implement in order to define how an object compares with the supplied object -
When you define the compareTo() method in your classes, you need to make sure that the return value of this method is -
negative, if this object is less than the supplied object.
zero, if this object is equal to the supplied object.
positive, if this object is greater than the supplied object.
Many predefined Java classes like String, Date, LocalDate, LocalDateTime etc implement the Comparable interface to define the ordering of their instances.
Let’s now see an example to make things more clear.
Example 1:
publicclassPersonimplementsComparable<Person> {privateString name;privateint age;publicPerson(String name,int age) {this.name= name;this.age= age; }publicintgetAge() {returnthis.age; }publicStringgetName() {returnthis.name; } @OverridepublicStringtoString() {return""; } @OverridepublicintcompareTo(Person per) {if (this.age==per.age)return0;elsereturnthis.age>per.age?1:-1; }publicstaticvoidmain(String[] args) {Person e1 =newPerson("Mohit",25);Person e2 =newPerson("Rahul",33);int retval =e1.compareTo(e2);switch (retval) {case-1: {System.out.println("The "+e2.getName() +" is older!");break; }case1: {System.out.println("The "+e1.getName() +" is older!");break; }default:System.out.println("The two persons are of the same age!"); } }}
The Rahul is older!
Java Comparable interface Example 2
The example below shows how to implement the Comparable interface in a user defined class and define the compareTo() method to make the objects of that class comparable.
importjava.time.LocalDate;publicclassEmployeeimplementsComparable<Employee> {privateint id;privateString name;privatedouble salary;privateLocalDate joiningDate;publicEmployee(int id,String name,double salary,LocalDate joiningDate) {this.id= id;this.name= name;this.salary= salary;this.joiningDate= joiningDate; }publicintgetId() {return id; }publicvoidsetId(int id) {this.id= id; }publicStringgetName() {return name; }publicvoidsetName(String name) {this.name= name; }publicdoublegetSalary() {return salary; }publicvoidsetSalary(double salary) {this.salary= salary; }publicLocalDategetJoiningDate() {return joiningDate; }publicvoidsetJoiningDate(LocalDate joiningDate) {this.joiningDate= joiningDate; }// Compare Two Employees based on their ID /** * @param anotherEmployee - The Employee to be compared. * @return A negative integer, zero, or a positive integer as this employee * is less than, equal to, or greater than the supplied employee object. */ @OverridepublicintcompareTo(Employee anotherEmployee) {returnthis.getId() -anotherEmployee.getId(); }}
In the above example, we’re comparing two employees by their IDs.
We’re just returning this.getId() - anotherEmployee.getId() from the compareTo() function, which will be
negative if the ID of this employee is less then the ID of the supplied employee,
zero if the ID of this employee is equal to the ID of the supplied employee, and
positive if the ID of this employee is greater than the ID of the supplied employee.
It’s just a concise way of writing the following -
Let’s now see how the Employee objects can be sorted automatically by Collections.sort method -
importjava.time.LocalDate;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;publicclassComparableExample {publicstaticvoidmain(String[] args) {List<Employee> employees =newArrayList<>();employees.add(newEmployee(1010,"Rajeev",100000.00,LocalDate.of(2010,7,10)));employees.add(newEmployee(1004,"Chris",95000.50,LocalDate.of(2017,3,19)));employees.add(newEmployee(1015,"David",134000.00,LocalDate.of(2017,9,28)));System.out.println("Employees (Before Sorting) : ");for(int i =0 ; i <employees.size(); i++) {System.out.println("id "+employees.get(i).getId());System.out.println("name "+employees.get(i).getName());System.out.println("salary "+employees.get(i).getSalary());System.out.println("joiningDate "+employees.get(i).getJoiningDate()); }// This will use the `compareTo()` method of the `Employee` class to compare two employees and sort them.Collections.sort(employees);System.out.println("\nEmployees (After Sorting) : ");for(int i =0 ; i <employees.size(); i++) {System.out.println("id "+employees.get(i).getId());System.out.println("name "+employees.get(i).getName());System.out.println("salary "+employees.get(i).getSalary());System.out.println("joiningDate "+employees.get(i).getJoiningDate()); } }}