Comparison between Comparable and Comparator based on Java

Posted by kevo1162 on Thu, 17 Feb 2022 05:25:03 +0100

Comparison between Comparable and Comparator in Java

Introduction to Comparable

Comparable is a sort interface.

If a class implements the Comparable interface, it means that "this class supports sorting". That is, classes that implement the Comparable interface support sorting. Assuming that there is a "List (or array) of objects of classes that implement the Comparable interface", the List (or array) can be through collections Sort (or Arrays.sort).

In addition, the object of the class implementing the Comparable interface can be used as a key in an ordered map (such as TreeMap) or an element in an ordered set (TreeSet), without specifying a comparator.

Comparable definition

The Comparable interface only includes one function, which is defined as follows:

package java.lang;
import java.util.*;

public interface Comparable<T> {
    public int compareTo(T o);
}

explain:
Suppose we use x.compareTo(y) to "compare the size of x and Y".

  • If "negative number" is returned, it means "x is smaller than y";
  • Return "zero", which means "x equals y";
  • Returns a positive number, meaning "x is greater than y".

Introduction to Comparator

Comparator is the comparator 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); Then, we can create 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 the Comparator class", and then sort the classes through the Comparator.

Comparator definition

Comparator interface only includes two functions, which are defined as follows:

package java.util;

public interface Comparator<T> {

    int compare(T o1, T o2);

    boolean equals(Object obj);
}

explain:

  • If a class wants to implement the Comparator interface: it must override the compareTo(T o1, T o2) function, but it can not implement the equals(Object obj) function.

Why not implement the equals(Object obj) function? Because any class has implemented equals(Object obj) by default. All classes in Java inherit from Java Lang.Object, in object The equals(Object obj) function is implemented in Java; Therefore, all other classes also implement the function.

The difference between Comparator and Comparable

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

It is not difficult to find that Comparable is equivalent to "internal Comparator" and Comparator is equivalent to "external Comparator".

We describe the two interfaces through a test program. The source code is as follows:

Implement the Comparable interface and rewrite compareTo

package wenhua.project;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author wenhua
 * @date 2022 10:21, February 17
 */
public class Person implements Comparable<Person>{

    // Declare properties
    private int age ;
    private String name;

    // Generation construction method
    public Person() {}

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    /**
     * Implement the Comparable interface and rewrite the compareTo method
     * @param person
     * @return
     */
    @Override
    public int compareTo(Person person) {
        // Implement class sorting
        return name.compareTo(person.name);// Equivalent to this. Return name - person. name;

    }

    public static void main(String[] args) {
        // New ArrayList (dynamic array)
        ArrayList<Person> list = new ArrayList<Person>();
        // Add objects to ArrayList
        list.add(new Person(20,"ccc"));
        list.add(new Person(30,"AAA"));
        list.add(new Person(10,"bbb"));
        list.add(new Person(40,"ddd"));
       System.out.println("Before sorting:"+list.toString());
        // Sort by calling sort through the collection static class Collections
        Collections.sort(list);
        System.out.println("After sorting:"+list.toString());

}

Operation results:

Before sorting:[Person{age=20, name='ccc'}, Person{age=30, name='AAA'}, Person{age=10, name='bbb'}, Person{age=40, name='ddd'}]
After sorting:[Person{age=30, name='AAA'}, Person{age=10, name='bbb'}, Person{age=20, name='ccc'}, Person{age=40, name='ddd'}]

Implement Comparator and rewrite the compare method

package wenhua.project;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author wenhua
 * @date 2022 10:21, February 17
 */
public class Person implements Comparator<Person> {

    // Declare properties
    private int age ;
    private String name;

    // Generation construction method
    public Person() {}
    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    // Generate get method
    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    /**
     * Implement the Comparator interface and rewrite the compare method
     * @param o1
     * @param o2
     * @return
     */
    @Override
    public int compare(Person o1, Person o2) {
        // Ascending order
        return o1.getAge()-o2.getAge();
    }

    public static void main(String[] args) {
        // Specifies a comparator to sort the specified array of objects
        Person[] list = new Person[4];
        list[0] = new Person(20,"ccc");
        list[1] = new Person(30,"AAA");
        list[2] = new Person(10,"bbb");
        list[3] = new Person(40,"ddd");
        // Note at this time, the length of the array is consistent with the length of the stored data, otherwise a runtime error occurs: NullPointerException

        /* Mode 1:
            Create a subclass person (data type of array) that implements the Comparator interface, which has sorting function, and override its compare method
        */
        Arrays.sort(list,new Person());
        System.out.println("Mode 1: ascending output:"+Arrays.toString(list));

        /* Mode 2:
            Directly implement the Comparator interface, create anonymous objects, and override the compare method
        */
        Arrays.sort(list,new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o2.getAge()-o1.getAge();// Descending order
            }
        });
        System.out.println("Mode 2: output in descending order:"+Arrays.toString(list));

    }

}

Operation results:

Mode 1: ascending output:[Person{age=10, name='bbb'}, Person{age=20, name='ccc'}, Person{age=30, name='AAA'}, Person{age=40, name='ddd'}]
Mode 2: output in descending order:[Person{age=40, name='ddd'}, Person{age=30, name='AAA'}, Person{age=20, name='ccc'}, Person{age=10, name='bbb'}]

summary

The Comparable interface implements and rewrites its compareTo method directly through collections Sort (object o) or arrays Call the sort (object o) method, otherwise an error will be reported.
The Comparator interface can be implemented as a sort class when calling arrays When sort(), you must pass in the Comparator of the object (or subclass of the object) of the new Comparator interface.

Reference article: https://www.cnblogs.com/skywang12345/p/3324788.html

Topics: Java JavaSE comparator