Difference between Comparator and Comparable
Java has two interfaces that you can use for sorting custom objects. These are the Comparator and Comparable interface. In this article, I will be explaining the differences between the two. Basic difference between Comparator and Comparable The main difference between the Comparator and Comparable interface is that you can use Comparator to compare two independent objects. The Comparable on the other hand is used to compare the current object with another object. Consider the following Person class: public class Person { private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; }} Suppose you want to sort Person objects on the basis of the age fields. Let us understand how you can achieve this using both Comparator and Comparable. Sorting Using Comparator In order to sort using Comparator, you will first need to create a class that implements the Comparator interface. The following code demonstrates this