当前位置:网站首页>类的比较大小(Comparable -> compareTo(类自己实现接口),Comparator -> compare(新建一个类作为比较器))

类的比较大小(Comparable -> compareTo(类自己实现接口),Comparator -> compare(新建一个类作为比较器))

2022-08-02 15:05:00 学习追求高效率

7. 比较大小的接口

1. Comparable -> compareTo

这个是在类里面定义比较函数,要比较的时候,调用的是比较函数,但是这个就会限制比较的条件,所以比较器更方便一点

在这里插入图片描述

1.1 sort排序

1.1.1 Compara接口实现后,可以用sort之间排序

1.1.2 排序前后可用用 toString 输出数组

在这里插入图片描述

class Student implements Comparable<Student>{
    
    public String name;
    public int age;
    public double score;

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

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

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


public class Test {
    
    public static void main(String[] args) {
    
        Student[] students = new Student[3];
        students[0] = new Student("bit",10,78.9);
        students[1] =  new Student("abc",4,98.9);
        students[2] =  new Student("gb",14,38.9);
        System.out.println("排序前"+Arrays.toString(students));
        sort(students);
        System.out.println("排序后"+Arrays.toString(students));
    }
}

1.1.3 sort排序规则

前 - 后 是从小到大
后 - 前 是从大到小

2. 比较器 Comparator -> compare

//比较器
class AgeComparator implements Comparator<Student> {
    
    @Override
    public int compare(Student o1, Student o2) {
    
        return o1.age-o2.age;
    }
}

class ScoreComparator implements Comparator<Student> {
    
    @Override
    public int compare(Student o1, Student o2) {
    
        return (int)(o1.score-o2.score);
    }
}

class NameComparator implements Comparator<Student> {
    
    @Override
    public int compare(Student o1, Student o2) {
    
        return o1.name.compareTo(o2.name);
    }
}

    public static void main8(String[] args) {
    
        Student[] students = new Student[3];
        students[0] = new Student("bit",10,78.9);
        students[1] =  new Student("abc",4,98.9);
        students[2] =  new Student("gb",14,38.9);
        System.out.println("排序前"+Arrays.toString(students));

        AgeComparator ageComparator = new AgeComparator();
        ScoreComparator scoreComparator = new ScoreComparator();
        NameComparator nameComparator = new NameComparator();

        Arrays.sort(students,nameComparator);

        System.out.println("排序后"+Arrays.toString(students));
    }

补充:String自带compareTo 用于字符串比较

class NameComparator implements Comparator<Student> {
    
    @Override
    public int compare(Student o1, Student o2) {
    
        return o1.name.compareTo(o2.name);
    }
}
原网站

版权声明
本文为[学习追求高效率]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_63571404/article/details/126088582