Java - Interview Questions and Answers on Comparable and Comparator

Q1.  What is the difference between comparable and comparator in java.util pkg?

Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data member where as comparator interface is used to sort the object based on multiple data members.

Q2.  What is comparator interface used for ?

Ans. The purpose of comparator interface is to compare objects of the same class to identify the sorting order. Sorted Collection Classes ( TreeSet, TreeMap ) have been designed such to look for this method to identify the sorting order, that is why class need to implement Comparator interface to qualify its objects to be part of Sorted Collections.

Q3.  How TreeMap orders the elements if the Key is a String ?

Ans. As String implements Comparable, It refers to the String compareTo method to identify the order relationship among those elements.