Comparable VS Comparator in Java.

Java util package provides us number of sorted data structures; one of those is the TreeSet. TreeSet is an implementation of Set and it stores the elements in sorted order. All elements needs to be added into a TreeSet should implement Comparable interface directly or indirectly or the TreeSet should be constructed with an appropriate Comparator. Since you are implementing the Comparable interface you are forced to implement the compareTo method. Normally the compareTo method is used to write most obvious/natural comparison logic for given object. In the below given example I have used the employeeId to compare two employees.

If you want to use a different attribute other than what is written in the compareTo method then you will have to write a Comparator for it. EmployeeNameComparator class is used to compare two employee instances using its name attribute. When you use a comparator you must pass that as the constructor argument for TreeSet.

The first example in the program sorts a collection of String using the sorted data structure TreeSet. Since the String implementation is comparable, elements are sorted in the natural order. In the second example the user defined class Employee is sorted using the TreeSet, this time the compareTo method is the Employee class is being called every time when you add an element into TreeSet to determine its position. In the third example a Comparator is being used to sort the employees based on their name. In the fourth example DepartmentName comparator is being used to sort the department objects. The last example throws an exception saying that the elements are not comparable. You can see that the Department class is not comparable since it’s not implementing the Comparable interface. In that case, we should have supplied a Comparator to the TreeSet to sort its elements.

Console Output.

One thought on “Comparable VS Comparator in Java.