For predefined comparable classes (String) default natural sorting order already available. If we are not satisfied with that default natural sorting order, then we can define our own sorting by using Comparator Interface.
For predefined non comparable classes StringBuffer default natural sorting order not already available, we can define our own sorting technique by using Comparator Interface.
For our own classes (like Employee, Student) the person who is writing the Class is responsible to define default natural sorting order by implementing comparable (Interface). The person who is using our Class, if he is not satisfied with the default natural sorting order then he can define his own sorting by using Comparator Interface.
Let’s take another example :
import java.util.*; class Employee implements Comparable /* Our custom object class which is comparable * as we are implementing comparable interface */ { String name; int id; Employee(String n, int i) // Employee class’s constructor { name = n; id = i; } public String toString() // Overridden toString() method { return name + “→” + id; } public int compareTo(Object obj) // implemented compareTo() method { int i1 = this.id; Employee em = (Employee)obj; int i2 = em.id; if(i1<i2) return -1; else if(i1>i2) return 1; else return 0; } } class Compar // Main driver class containing main method { public static void main(String[] args) { Employee e1 = new Employee(“Rajesh”,001); Employee e2 = new Employee(“Rahul”,002); Employee e3 = new Employee(“Pratap”,003); Employee e4 = new Employee(“Kedar”,004); TreeSet t1 = new TreeSet(); /* As we are not passing any custom comparator * object as argument in the TreeSet constructor * so default natural sorting order will be followed, * here objects will be sorted as per their id number */ t1.add(e1); t1.add(e2); t1.add(e3); t1.add(e4); System.out.println(t1); TreeSet t2 = new TreeSet(new myComp()); /* As we are passing our custom * comparator object as argument in * the TreeSet constructor so default natural * sorting order will not be followed, our * custom sorting order will be followed, * in which objects will be sorted alphabetically. */ t2.add(e1); t2.add(e2); t2.add(e3); t2.add(e4); System.out.println(t2); } } class myComp implements Comparator // Our custom comparator class { public int compare(Object obj1, Object obj2) { Employee em1 = (Employee)obj1; Employee em2 = (Employee)obj2; String s1 = em1.name; String s2 = em2.name; return s1.compareTo(s2); } }
If we run this code, we will get the following output :
[Rajesh→1, Rahul→2, Pratap→3, Kedar→4] [Kedar→4, Pratap→3, Rahul→2, Rajesh→1]
This tutorial covers all the concept of Comparable and Comparator Interface from the Java interview question perspective.