In Java, the Comparator interface is used to define a custom way to compare objects.
The Comparator interface actually has two methods:
* equals(Object obj): This method checks if the specified object is equal to the Comparator. The method returns true if the object is equal to the Comparator, and false otherwise.
The equals(Object obj) method has the following signature:
boolean equals(Object obj)
* compare(T o1, T o2): This method compares two objects of type T and returns an integer value that indicates the order of the objects. The method returns a negative integer if o1 is less than o2, zero if o1 is equal to o2, or a positive integer if o1 is greater than o2.
The compare() method has the following signature:
int compare(Object o1, Object o2)
Here, o1 and o2 are the objects that need to be compared. The method returns an integer value that indicates the relationship between the two objects. Specifically, it returns:
* A negative integer if o1 is less than o2
* Zero if o1 is equal to o2
* A positive integer if o1 is greater than o2
To use the Comparator interface, you need to create a class that implements this interface and provide your own implementation of the compare() method. Here's an example:
import java.util.*;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class AgeComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Alice", 20));
studentList.add(new Student("Bob", 19));
studentList.add(new Student("Charlie", 21));
Collections.sort(studentList, new AgeComparator());
for (Student student : studentList) {
System.out.println(student.getName() + " " + student.getAge());
}
}
}
In this example, we have a Student class with a name and age field. We want to sort a list of Student objects by age. To do this, we create a new class called AgeComparator that implements the Comparator interface with a compare() method that compares two Student objects by their age.
We then create a List of Student objects and use the Collections.sort() method to sort it using our AgeComparator. Finally, we iterate over the sorted list and print out the name and age of each Student object.
In practice, the equals() method is rarely used, and the compare() method is the main method that is implemented when using the Comparator interface.