In Java, the Comparator
interface and the Comparable
interface play a crucial role in sorting collections of objects. These interfaces provide a way to define custom sorting order for objects based on specific criteria.
Let's start by looking at the Comparable
interface. This interface allows objects of a class to be compared with each other. To implement the Comparable
interface, a class must define a method called compareTo()
.
Here's an example implementation of the Comparable
interface for a Person
class:
1class Person implements Comparable<Person> {
2 private String name;
3 private int age;
4
5 public Person(String name, int age) {
6 this.name = name;
7 this.age = age;
8 }
9
10 public String getName() {
11 return name;
12 }
13
14 public int getAge() {
15 return age;
16 }
17
18 @Override
19 public int compareTo(Person otherPerson) {
20 // Compare based on age
21 return Integer.compare(this.age, otherPerson.getAge());
22 }
23}
In the above code, the Person
class implements the Comparable<Person>
interface. The compareTo()
method is overridden to compare two Person
objects based on their age.
Once a class implements the Comparable
interface, objects of that class can be sorted using methods like Collections.sort()
or Arrays.sort()
.
Now, let's move on and explore the Comparator
interface. Unlike the Comparable
interface, the Comparator
interface allows us to define different comparison criteria without modifying the class itself. This is useful when we need to sort objects based on multiple attributes or when sorting objects from external libraries.
To implement the Comparator
interface, we need to define a class that implements the Comparator<T>
interface and override the compare()
method.
Here's an example implementation of the Comparator
interface for the Person
class that compares objects based on their name:
1import java.util.Comparator;
2
3class PersonComparatorByName implements Comparator<Person> {
4 @Override
5 public int compare(Person person1, Person person2) {
6 // Compare based on name
7 return person1.getName().compareTo(person2.getName());
8 }
9}
In the above code, the PersonComparatorByName
class implements the Comparator<Person>
interface. The compare()
method is overridden to compare two Person
objects based on their names.
To use the Comparator
for sorting, we can pass an instance of the Comparator
class to the sort()
method.
1List<Person> people = new ArrayList<>();
2people.add(new Person("John", 25));
3people.add(new Person("Alice", 30));
4people.add(new Person("Bob", 20));
5
6Collections.sort(people, new PersonComparatorByName());
7
8for (Person person : people) {
9 System.out.println(person.getName());
10}