How to sort and compare complex data types in Java

Table of contents

 1. Comparing the size of complex data types

Comparable interface

compareTo method 

2. Sorting complex data types

3. Summary


 1. Comparing the size of complex data types

If we now have a student class, and we instantiate two student objects, each of them has its own name and age attributes, how do we compare them?

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

public class Test{
    public static void main(String[] args) {
        Student student1 = new Student("张三",20);
        Student student2 = new Student("李四",23);   
        if (student1 > student2) {
            System.out.println("student1 > student2");
        }else {
            System.out.println("student1 < student2");
        }
    }
}

We can see the compiler's error message. This is because the operation symbols provided by Java can only recognize simple data types. For our customizedStudent class is unrecognizable

Comparable interface

In this case, we can use the knowledge of the interface we explained before. We can callComparable interface, and then restart Write the compareTo method. When using the interface, you need to pay attention to declaring the type you need to compare, that is, the content within the angle brackets after the interface

compareTo method 

Here we rewrite the compareTo method in the interface and call it in the main method 

class Student implements Comparable <Student> {
    public String name;
    public int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);
    }
}

public class Test{

    public static void main(String[] args) {
        Student student1 = new Student("张三",20);
        Student student2 = new Student("李四",23);

        if (student1.compareTo(student2) > 0) {
            System.out.println("student1 > student2");
        }else {
            System.out.println("student1 <= student2");
        }
    }
}

We can also perform size comparison based on age. We just need to rewrite this method.

    @Override
    public int compareTo(Student o) {
        return this.age-o.age;
    }

2. Sorting complex data types

If we now have an array of students, we use Arrays.sort to sort it

public class Test{

    public static void main(String[] args) {
        Student[] students = new Student[3];
        Student student1 = new Student("张三",20);
        Student student2 = new Student("李四",23);
        Student student3 = new Student("王五",25);
        students[0] = student1;
        students[1] = student2;
        students[2] = student3;
        
        Arrays.sort(students);
      
    }
}

We will find the error message as follows. The reason is that for this complex data type, if we want the compiler to sort it, then we need to give it the sorting rules. Obviously the compiler has not read any sorting rules here.

When we click on the error message, open the source code and observe, we will find that the compiler still uses the Comparable interface hereComparable interface

Then we still call the Comparable interface as before, and then we give clear sorting rules and write a sorting method. Complex data is sorted normally

import java.util.Arrays;

class Student implements Comparable <Student> {
    public String name;
    public int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
//    @Override
//    public int compareTo(Student o) {
//        return this.name.compareTo(o.name);
//    }
    @Override
    public int compareTo(Student o) {
        return this.age-o.age;
    }
    
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public static void mySort(Comparable[] comparables) {

        for (int i = 0; i < comparables.length-1; i++) {
            for (int j = 0; j < comparables.length-1-i; j++) {
                //if(comparables[j] > comparables[j+1]) {
                if(comparables[j].compareTo(comparables[j+1]) > 0) {
                    //交换
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j+1];
                    comparables[j+1] = tmp;
                }
            }
        }
    }
}

public class Test{

    public static void main(String[] args) {
        Student[] students = new Student[3];
        Student student1 = new Student("张三",20);
        Student student2 = new Student("李四",23);
        Student student3 = new Student("王五",25);
        students[0] = student1;
        students[1] = student2;
        students[2] = student3;
        
        mySort(students);
        System.out.println(Arrays.toString(students));
       
    }
}

3. Summary

When we need to sort or compare complex data types, we can use Comparable interface and then rewrite it compareTo method, and then you can directly use compareTo method for sorting , or call the compareTo method through other methods to sort complex type arrays

Guess you like

Origin blog.csdn.net/m0_69519887/article/details/134409044