Comparable interface usage of Java foundation

        Java is sorted by the Comparable and Comparator two interfaces to provide.

        Comparable representation may be sorted, an object that implements the interface class automatically have the sorting function.

        Comparator indicates a comparator, the object's class implements the interface for the target object is a class defined by the comparator, in general, the more will be passed as a parameter.

 

(一)Comparable

        Comparable means that the Chinese may be ordered, on behalf of itself supports sorting. As long as our class implements this interface, the object of this class will automatically have the ability to be sorted. And this is called the natural order sorting class. List of objects of this class can be Collections.sort and Arrays.sort to do the sorting. At the same time instance of this class are qualified and a key element of the sorted set of sorted map.

        If a and b are realized Comparable interface instance of a class C, and then only when the results are consistent a.compareTo (b) results with a.equals (b), the only known natural order consistent with equals class C. It is strongly recommended natural order of class and equals the result of consistent, because if not, then by the class object of the key and sorted map sorted set by this class object is an element of behavior will become very strange.

        For example, one implementation of an ordered collection of sorted set Comparable interface element, if a.equals (b) evaluates to false, and a.compareTo (b) == 0, then the operation will add a second element failed because the sorted set view, the two are identical in the sort, it does not save the newspaper repeated elements.

        In fact, Java classes are basically the same and equals the natural order, BigDecimal addition, because the natural order, and the same values ​​in BigDecimal, but the accuracy equals different elements (e.g. 4 and 4.00) are consistent. 


        Source Analysis:

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

        You can see from the source code, the interface is only an abstract method compareTo, this method is mainly to define our class to be sort of way. compareTo method for comparing the current element with a specified element B, the result is an int, if a> b, int> 0; if a = b, int = 0; if a <b, int <0.

       Example of use:

class Student implements Comparable<Student>{
    int sno;
    int score;
 
    Student(int sno,int score){
        this.sno = sno;
        this.score = score;
    }
 
    @Override
    public int compareTo(Student o) {
        if(this.score<o.score) return -1;
        else if(this.score>o.score) return 1;
        else return 0;
    }
}

 

(B) Comparator

       Comparator translated Chinese comparator which can be passed as a parameter to the method to specify Arrays.sort Collections.sort and ordering a class object. It also can be sorted set and sorted map to specify the sort.

        Comparable with similarly specified comparator when general but also to ensure a consistent comparison of results equals results, inconsistent, then the corresponding sorted set sorted map and behavior will also become weird.

        Source Analysis:

@FunctionalInterface
public interface Comparator<T> {
    // 需要实现的抽象方法,用于定义比较方式(即排序方式)
    // o1>o2,返回1;o1=o2,返回0;o1<o2,返回-1
    int compare(T o1, T o2);

    boolean equals(Object obj);
}

        Recommended achieve comparator also implement java.io.Serializable interface, ability to have a sequence, as it may be used as a serialized data structure (TreeSet, the TreeMap) sorting method.   

        Special Note: achieve only compare method Comparator interface, the need to achieve, but do not achieve the equals method. The reason is: Java classes inherit from the Object class, and the default implementation of the Object class equals method, so no need to implement the equals method.

 

(C) comparing the two

        Comparable can be seen as an internal comparator, Comparator can be seen as an external comparator.

        A class can be implemented by ordering from the band Comparable interface, you may also be an additional ordering specified by the additional Comparator.

        In fact, the role of both is the same, so do not mix.

For example:

public class User implements Serializable, Comparable<User> {
    private static final long serialVersionUID = 1L;
    private int age;
    private String name;
 
    public User (){}
 
    public User (int age, String name){
        this.age = age;
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public int compareTo(User o) {
        return this.age - o.age;
    }
 
    @Override
    public String toString() {
        return "[user={age=" + age + ",name=" + name + "}]";
    }
}
public class MyComparator implements Comparator<User> {
    @Override
    public int compare(User o1, User o2) {
        return o1.getName().charAt(0)-o2.getName().charAt(0);
    }
}

       Test categories:

public class Main {
 
    public static void main(String[] args) {
        User u1 = new User(12, "xiaohua");
        User u2 = new User(10, "abc");
        User u3 = new User(15,"ccc");
        User[] users = {u1,u2,u3};
        System.out.print("数组排序前:");
        printArray(users);
        System.out.println();
        Arrays.sort(users);
        System.out.print("数组排序1后:");
        printArray(users);
        System.out.println();
        Arrays.sort(users, new MyComparator());
        System.out.print("数组排序2后:");
        printArray(users);
        System.out.println();
        Arrays.sort(users, Comparator.reverseOrder());// 针对内置的排序进行倒置
        System.out.print("数组排序3后:");
        printArray(users);
    }
 
    public static void printArray (User[] users) {
        for (User user:users) {
            System.out.print(user.toString());
        }
    }
}

       Note: The definition of the sort of two ways priority , Comparator comparator should take precedence over internal sorting the Comparable .

 

Published 35 original articles · won praise 37 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_34519487/article/details/103931033