Java的Comparable接口&比较器原理

版权声明:欢迎转载! https://blog.csdn.net/wangwenhao00/article/details/73656336

对需要进行排序的对象实现Comparable接口,重写其中的compareTo(T o)方法,在其中定义排序规则,那么就可以直接调用java.util.Arrays.sort()来排序对象数组
需求:设计一个学生类, 属性有姓名,年龄, 成绩,并产生一个数组,要去安装成绩从高到低,如果成绩相等则有年龄有第到高排序。

import java.util.Arrays;
class Student implements Comparable<Student>{
    private String name;
    private int age;
    private float score;
    public Student(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public String toString() {
        return name + " " + age + " " + score;
    }
    public int compareTo(Student stu) {
        if(this.score > stu.score)  {
            return -1;
        } else if(this.score < stu.score) {
            return 1;
        } else {
            if(this.age > stu.age) {
                return 1;
            } else if(this.age < stu.age) {
                return -1;
            } else {
                return 0;
            }
        }
    }
}

public class ComparableDemo {
    public static void main(String[] args) {
        Student students[] = {new Student("张三", 20, 90.0f), new Student("李四", 22, 90.0f),
                new Student("王五", 20, 99.0f), new Student("赵六", 20, 70.0f), new Student("孙七", 22, 100.0f)};
        Arrays.sort(students);
        for (Student stu: students) {
            System.out.println(stu);
        }
    }

}

下面是Arrays类一些方法的demo, 点击Arrays类查看其方法的声明.

public class ArraysDemo {
    public static void main(String[] args) {
        int temp[] = {3, 5, 7, 9, 1, 2, 6, 8};
        Arrays.sort(temp);
        System.out.print("排序后的结果:");
        System.out.println(Arrays.toString(temp));
        int point = Arrays.binarySearch(temp, 3); 
        System.out.println("元素3的位置在: " + point);
        Arrays.fill(temp, 0);
        System.out.println("数组填充:" + Arrays.toString(temp));

    }
}
展开阅读全文

没有更多推荐了,返回首页