One of the general interview question asked by the interviewer is “state the differences between comparator and comparable in java” or else “how will you able to arrange group of employee objects via its name or ID. To arrange so, you need to create two interfaces like comparable and comparator.  Before going discuss about the difference between them we need to know what does comparable interface in java, and what is comparator in Java.

Comparator vs Comparable

Comparator

1) Comparator is coming from the java.util package.

2) In comparator, a class whose objects need to be arranged does not include this interface. Where as, other class can include this interface from which the properties are sorted.

3) In comparator, the sorting logic takes place in different classes and you need to write different sorting according to the attributes of the object which are going to be sorted

4) In comparative interface, it is int compare(Object o1,Object o2)

5) In comparative method, it is called by Collections.sort(List, Comparator). In this case, the objects will be arranged depending upon compare method found in the comparator.

6) In comparative method, it compares the o1 and 02 objects and hence returns an integer value.

Comparable

1) Where as Comparable is coming from the java.lang package.

2) In Comparable, a class whose objects are to be sorted must include this Comparable Interface.

3) In comparable interface, the sorting logic will takes place in similar class whose objects are going to be arranged.

5) The sorting method in comparable interface is int compareTo(Object o1)

4) Comparable interface can be called by Collections.sort(List). In this case, the objects will be arranged depending upon CompareTo method.

6) In comparable method, it compares this object with o1 object and hence returns an integer as output