一.比较器的使用
代码语言: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
- 如果返回的是负数,那么对象o1在前面;
- 如果返回的是正数,那么对象o2在前面;
上面程序输出:
Student{age=12, name='lvachao', height=23}
Student{age=34, name='lvaco', height=87}
Student{age=14, name='lvacha', height=678}