比较器的使用

2019-02-18 11:24:46 浏览数 (1)

一.比较器的使用

代码语言:javascript复制
private static class Student{
    int age;
    String name;
    int height;

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

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

private static class isIncrease implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.height - o2.height;
    }
}

main函数里面:

代码语言:javascript复制
Student[] students = new Student[]{
        new Student(12,"lvachao",23),
        new Student(14,"lvacha",678),
        new Student(34,"lvaco",87),
};

Arrays.sort(students,new isIncrease());
for (Student student : students){
    System.out.println(student);
}

定义一个student类,然后定义一个isIncrease类继承Comparator<Student>接口,注意这里的泛型的类型要添加上Student

  1. 如果返回的是负数,那么对象o1在前面;
  2. 如果返回的是正数,那么对象o2在前面;

代码语言:javascript复制
上面程序输出:
Student{age=12, name='lvachao', height=23}
Student{age=34, name='lvaco', height=87}
Student{age=14, name='lvacha', height=678}

0 人点赞