Nov 10, 2018

Difference between Comparator and Comparable in Java

Comparator and Comparable are two interfaces in Java API. Though both are used for comparison there are some difference between them.

Comparator vs Comparable in Java

1. Comparator interface is in java.util package, which implies it's a utility class, while Comparable interface is kept on java.lang package, which means it's essential for Java objects.

2. Based on syntax, one difference between Comparable and Comparator in Java is that former gives us compareTo(Object toCompare), which accepts an object, which now uses Generics from Java 1.5 onwards, while Comparator defines compare(Object obj1, Object obj2) method for comparing two object.

3. Comparable is used to compare current object, represented by this keyword, with another object, while Comparator compares two arbitrary object passed to compare() method in Java.

4. You can only have one compareTo() implementation for an object, while you can define multiple Comparator for comparing objects on different parameters e.g. for an Employee object, you can use compareTo() method to compare Employees on id,  known as natural ordering, while multiple compare() method to order employee on age, salary, name and city. It's also a best practice to declare Comparator as nested static classes in Java, because they are closely associated with objects they compare.

5. Many Java classes, which make uses of Comparator and Comparable defaults to Comparable and provided overloaded method to work with arbitrary Comparator instance e.g. Collections.sort() method, which is used to sort Collection in Java has two implementation, one which sorts object based on natural order i.e. by using java.lang.Comparable and other which accepts an implementation of java.util.Comparator interface.

6. Both compareTo() and compare() method in Java must be consistent with equals() implementation i.e. if two methods are equal by equals() method than compareTo() and compare() must return zero. Failing to adhere this guideline, your object may break invariants of Java collection classes which rely on compare() or compareTo() e.g. TreeSet and TreeMap.

Conclusion: Always remember that java.lang.Comparable is used to define natural ordering of an object, while java.util.Comparator can be used to define any ordering based upon your requirements. You can define only one ordering with Comparable but can have multiple Comparators.