[java] In-depth understanding of natural sorting

Continue to create, accelerate growth! This is the first day of my participation in the "Nuggets Daily New Plan · June Update Challenge", click to view the details of the event

For int arrays, string arrays, they are easy to compare the size. You can write a quick sort algorithm yourself, or directly call the sorting interface Arrays.sort() in java to sort the array. But if we want to sort an array of objects, what should we do? As an object-oriented language, java will naturally not leave such gaps. We can even call the Arrays.sort() method on the array of objects to achieve sorting. function, this is called the java natural ordering.

/*
普通数组的排序
*/
public static void main(String[] args) {
    String[] strs = {"abc","ab","aa","ac"};
    System.out.println("strs = " + Arrays.toString(strs));
    Arrays.sort(strs);
    System.out.println("strs = " + Arrays.toString(strs));

    int[] ints = {1,4,6,2,7};
    System.out.println("ints = " + Arrays.toString(ints));
    Arrays.sort(ints);
    System.out.println("ints = " + Arrays.toString(ints));
}
复制代码

Obviously, when sorting the object array, you should point out the basis for the size of the object row, such as the id of the student object, grades, etc. can be used as the sorting basis. In order for the JVM to find this basis, we need to implement a sortable functional interface for the student class, so that we can distinguish which types of objects can be sorted and which types cannot.

This functional interface is the Comparable interface, which is an interface already given by java. We can look at the source code (using java8 as an example):

image.png

There is only one method to be implemented in this interface, called the compareTo method.

image.png

This method is the basis for sorting with Arrays.sort(). The functions to be implemented in the compareTo method are:

Compare the current object (this) with the specified object (that is, the parameter o passed in here). The return value is a negative integer, zero, or a positive integer because this object is less than, equal to, or greater than the specified object.

Now that the logic of compareTo has been given, we only need to specify which property of the object to use for sorting.

For example, let's specify the sorting basis for the student class with scores.

class Student implements Comparable<Student>{
    String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public int getScore() {
        return score;
    }

    @Override
    public String toString() {
        //toString方法体
    }

    @Override
    public int compareTo(Student o) {
        //认为分数高的学生排在后面,分数低的排前面
        return getScore()-o.getScore();
    }
}
复制代码

Next is the moment to witness the miracle! Once we implement the Comparable interface and override the compareTo method in the object's class, we can call Arrays.sort() to sort the object!

import java.util.Arrays;

public class Ex2 {
    public static void main(String[] args) {
        //创建学生对象数组
        Student[] students = new Student[4];
        students[0] = new Student("商见曜",100);
        students[1] = new Student("龙悦红",70);
        students[2] = new Student("蒋白棉",99);
        students[3] = new Student("白晨",88);
        Arrays.sort(students);
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

复制代码

image.pngThe basic use of natural sorting is almost the same here, but we can be more elegant. If the class we want to sort objects does not implement the compareable interface, do we have to re-modify the source code of the class to add a sorting function? This is too inelegant!

In fact, enter Arrays.sort in the idea, there are multiple methods to choose from, these methods constitute method overloading, one of which has two parameters:

image.png

The second parameter is the implementation subclass of a new functional interface, which is called Comparoter. Its function is similar to Comparable, and it also provides sorting basis when sort sorts objects. Its use method is to implement his subclass object separately, and then be called as a parameter in the sort method. At this time, we don't need to implement the comparable interface in the object's class (note! The comparable interface and the comparator interface are two interfaces!)

Arrays.sort(students,(o1,o2)->o1.getScore()-o2.getScore());
复制代码

The second parameter is the subclass object of the comparator interface, which is in the format of a lambda expression. The abstract method implemented here is the compare method in the comparator. The rules are the same as the compareTo method in Comparable, so I won't repeat them.

image.png

Guess you like

Origin juejin.im/post/7101598232563679263