Comparator and Comparable are two interfaces in Java API, which is used to compare two objects in Java. Though both are used for comparison there are some difference between them, major difference between
Comparable and
Comparator is that former is used to define natural ordering of object e.g. lexicographic order for
java.lang.String, while later is used to define any alternative ordering for an object. Main usage of
java.lang.Comparable and j
ava.util.Comparator interface is for
sorting list of objects in Java. For example to sort a list of
Employee by there Id, we can use Comparable interface and to provide additional sorting capability, we can define multiple comparators e.g.
AgeComparator to compare age of employee,
SalaryComparator to compare salary of employees etc. This brings another i
mportant difference between Comparator and Comparable interface in Java, you can have only one ordering via
Comparable e.g. natural ordering, while you can define multiple
Comparator for alternative ordering as discussed above. Coming to Interviews, this question is very common on
2 to 3 years experience Java interviews, and you just can't afford to not prepare this. It's definitely possible to achieve years of experience in Java, without writing your own Comparator or Comparable, especially if you are not doing active development or coding, but even though, you must know basics e.g.
equals and hashcode,
compareTo and compare. In this article, we will see some notable difference between Comparator vs Comparable in Java from interview perspective.