When to use comparable and comparator in java with example?
In case one wants a different sorting order then he can implement comparator and define its own way of comparing two instances. If sorting of objects needs to be based on natural order then use Comparable whereas if your sorting needs to be done on attributes of different objects, then use Comparator in Java.
🔗Reference: stackoverflow.com
🔗Source: Java Interview Questions and Answers