Comparator in java

Keywords: Java JavaSE

1, Introduction to Comparable

Comparable is a sort interface. If a class implements the comparable interface, it means that the class supports sorting. The list or array of objects of classes that implement the comparable interface can be automatically sorted through Collections.sort or Arrays.sort.

In addition, the object implementing this interface can be used as a key in an ordered map or a collection in an ordered collection without specifying a comparator. The interface is defined as follows:

package java.lang;
import java.util.*;
public interface Comparable<T> 
{
    public int compareTo(T o);
}

T represents the types of objects that can be compared with this object.

This interface has only one method compareTo to compare the order of this object with the specified object. If the object is less than, equal to or greater than the specified object, it will return a negative integer, zero or positive integer respectively.

Now let's assume a Person class with the following code:

public class Person
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }  public int getAge()
    {
        return age;
    }
}

Now there are two objects of the Person class. How can we compare their sizes?
We can make Person implement the Comparable interface:

public class Person implements Comparable<Person>
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    @Override
    public int compareTo(Person p)
    {
        return this.age-p.getAge();
    }
    public static void main(String[] args)
    {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println("Before sorting");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
        Arrays.sort(people);
        System.out.println("\n After sorting");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
    }
}

2, Introduction to Comparator
Comparator is a comparison interface. If we need to control the order of a class and the class itself does not support sorting (that is, it does not implement the Comparable interface), we can establish a "comparator of this class" to sort. This "comparator" only needs to implement the comparator interface. In other words, we can create a new comparator by implementing comparator, and then sort the classes through this comparator. The interface is defined as follows:

package java.util;
public interface Comparator<T>
 {
    int compare(T o1, T o2);
    boolean equals(Object obj);
 }

Note: 1. If a class wants to implement the Comparator interface, it must implement the compare(T o1, T o2) function, but it may not implement the equals(Object obj) function.

2. int compare(T o1, T o2) is "compare the size of o1 and o2". Return "negative number", which means "o1 is smaller than o2"; Return "zero", which means "o1 equals o2"; Returns a positive number, meaning o1 is greater than o2.

Now, if the Person class above does not implement the Comparable interface, how to compare the size? We can create a new class and let it implement the Comparator interface to construct a "Comparator".

public class PersonCompartor implements Comparator<Person>
{
    @Override
    public int compare(Person o1, Person o2)
    {
        return o1.getAge()-o2.getAge();
    }
}

Now we can use this comparator to sort them:

public class Person
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public static void main(String[] args)
    {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println("Before sorting");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
        Arrays.sort(people,new PersonCompartor());
        System.out.println("\n After sorting");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
    }
}

3, Comparison between Comparable and Comparator

Comparable is a sort interface. If a class implements the comparable interface, it means that "this class supports sorting". And Comparator is a Comparator. If we need to control the order of a class, we can create a "Comparator of this class" to sort.

Comparable is equivalent to "internal Comparator", while Comparator is equivalent to "external Comparator".

The two methods have their own advantages and disadvantages. Using Comparable is simple. As long as the object implementing the Comparable interface directly becomes a Comparable object, but the source code needs to be modified. The advantage of using Comparator is that it does not need to modify the source code, but implements another Comparator. When a user-defined object needs to be compared, the Comparator and the object are passed together The size can be compared, and in Comparator, users can implement complex and general logic to match some simple objects, which can save a lot of repetitive work.

Comparable makes elements comparative, and Comparator makes containers comparative

Posted by pulsedriver on Mon, 20 Sep 2021 21:50:34 -0700