...

/

Understanding Comparator Interface

Understanding Comparator Interface

Let's discuss the working of Comparator Interface.

We'll cover the following...

One of the major drawbacks of using a Comparable interface is that the comparing logic gets fixed. For instance, if we have a Vehicle class, then it can be sorted either on the basis of the brand or the production year depending on the implementation of the compareTo() method.

If we need some flexibility in sorting, we should use the Comparator interface instead of the Comparable interface. The Comparator interface has a method, compare(T o1, T o2) ...