The difference between Comparable and Comparator & some understanding of generics

Keywords: Java

The difference between Comparable and Comparator & some understanding of generics

Comparable interface

Look directly at the api

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

It can be seen that there is only one compareTo method in this generic interface, and the parameters are generic variables of the same type. If we need to use comparison or sorting methods, we only need to implement the following Comparable interface on this class and rewrite the compareTo method.
In addition, some basic types also implement the Comparable interface, such as Integer and String types.

This method returns data of type int, but the value of this int can only be the following three types:

1: Indicates greater than
-1: Indicates less than
0: Indicates equality

The method of use is also simple:

package Test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Node extends PeopleInSchool implements Comparable<Node>{
    @Override
    public int compareTo(Node o) {
        if(this.Id.compareTo(o.Id)>0) return 1;
        else if(this.Id.compareTo(o.Id)==0) return 0;
        else return -1;
    }

    public static void main(String[] args) {
        Node[] t = new Node[20];
        for(int i=0;i<20;i++) {
            Node node = new Node();
            node.Id = Test1.RandomId(1);  //Here is the randomly generated string function written by yourself, so I won't show it.
            t[i] = node;
        }
        Arrays.sort(t);
        for(int i=0;i<20;i++){
            System.out.println(t[i].Id+"    "+t[i].Name);
        }
    }
}

PeopleInSchool class:

package Test;

public class PeopleInSchool {
    public String Id;
    public String Name;
}

Operation results:

Comparator interface

Comparator interface, let's look at the api

public interface Comparator<T>{
    int compare(T o1, T o2);
    boolean equals(Object obj);  //Can not be achieved
}

Therefore, we only need to implement the following compare() method to compare the two classes, which is a bit like C + + custom sorting

//It is written in C + +:
bool cmp(node a,node b){
	if(a.id!=b.id) return a.id<b.id;
	else return a.name<b.name;
}
sort(a+1,a+1+n,cmp);

Analogy

package Test;

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

public class Node1 extends PeopleInSchool implements Comparator<Node1> {

    @Override
    public int compare(Node1 o1, Node1 o2) {
        if(o1.Id.compareTo(o2.Id)>0) return 1;
        else if(o1.Id.compareTo(o2.Id)==0) return 0;
        else return -1;
    }

    public static void main(String[] args) {
        Node[] t = new Node[20];
        for(int i=0;i<20;i++) {
            Node node = new Node();
            node.Id = Test1.RandomId(1);
            t[i] = node;
        }
        Arrays.sort(t);
        for(int i=0;i<20;i++){
            System.out.println(t[i].Id+"    "+t[i].Name);
        }
    }
}

Operation results:

There is a similar way of writing

public class Node1 extends PeopleInSchool {

//    @Override
//    public int compare(Node1 o1, Node1 o2) {
//        if(o1.Id.compareTo(o2.Id)>0) return 1;
//        else if(o1.Id.compareTo(o2.Id)==0) return 0;
//        else return -1;
//    }

    

    public static void main(String[] args) {
        Comparator<Node> cmp = new Comparator<Node>() {  //Interface instantiation
        @Override
        public int compare(Node o1, Node o2) {
            if(o1.Id.compareTo(o2.Id)>0) return 1;
            else if(o1.Id.compareTo(o2.Id)==0) return 0;
            else return -1;
        }
    };
        Node[] t = new Node[20];
        for(int i=0;i<20;i++) {
            Node node = new Node();
            node.Id = Test1.RandomId(1);
            t[i] = node;
        }
        Arrays.sort(t,cmp);
        for(int i=0;i<20;i++){
            System.out.println(t[i].Id+"    "+t[i].Name);
        }
    }
}

Comparing Comparable with comparator, Comparable can be regarded as an internal comparator. One feature of the classes that implement the Comparable interface is that these classes can be compared with themselves. Comparator can be regarded as an external comparator. For example, when sorting in multiple ways is required, multiple Comparator cmp can be defined.

The underlying principle of the comparator is obtained by traversing the binary search tree, and the time complexity is nlog(n).

Some understanding of generics

  • Write your own generic class and treat the generic as a class that can be replaced by Integer or String. When you need to use a generic class, replace it with the class you need
  • The function of generics is to let us find errors at compile time rather than at run time
  • For generic methods, I think generic parameters appear in function parameters

  • As shown in the figure below

    SortUtil in the figure is not a generic class, but it has two generic methods. If < T > after public is removed, it is equivalent to that the type T of List in the parameter is not declared, and an error will be reported

Generic generic

Generic types have three forms:? extends T,? super T, where t is a generic type

The first form? It is called unrestricted general distribution and has no restrictions. The second is called restricted wildcard, which represents t or a subclass of T. The third form? super T is called lower bound wildcard and represents t or the parent class of T.

For example, you can see page 11 of advanced JAVA language programming version 11. It is easy to understand, including the peoplesinschool mentioned above by Comparator, which uses restricted wildcard. T must be a subclass of peoplesinschool

After learning, update it again. There are many that won't

Posted by phpserver on Sat, 18 Sep 2021 01:08:53 -0700