版权声明:LemonSnm https://blog.csdn.net/LemonSnm/article/details/89762995
对象比较器
对两个或多个数据项进行比较,以确定它们是否相等,或确定它们之间的大小关系及排列顺序为比较。
1.Comparator
Comparator接口是要求自定义类去实现,按照OO原则;对修改关闭,对扩展开放。
如果这个类已经定义好了,不想去修改它,那么需要Comparator接口:强行对某个对象collection进行整体排序的比较。
已经定义好的Student类(不想修改):
package com.lemon;
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
自定义类ComparatorDemo.java
(实现Comparator接口,从而自定义排序规则)
import java.util.Comparator;
public class ComparatorDemo implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
//自定义排序规则
return o1.getAge() - o2.getAge();
}
}
测试:
Student[] stu = {new Student("贝贝",6),new Student("欢欢",4),new Student("妮妮",5)};
Arrays.sort(stu,new ComparatorDemo()); //排序规则
System.out.println(Arrays.toString(stu));
注意:
Arrays.sort(stu,new ComparatorDemo()); //排序规则
一定要带上自定义的排序规则类,否则报错 java.lang.ClassCastException