对象比较的三种方法
1、重写equals方法和hashCode方法
class Student{
public int age;
public String name;
public Student(int age,String name) {
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true; //判断对象引用相等
if (o == null || getClass() != o.getClass()) return false; //为空,或者不是同一个类
//两个对象都不为空或者是同一个类的对象
Student student = (Student) o; //转为该类
return this.id == student.id && this.name.equals(student.name); //判断值是否相等
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
注意:自定义类型都需要重写equals和hashCode方法。重写equals是为了方便对象进行比较,重写hashCode是为了找到对象存储的位置。
2、实现Comparable
class Student implements Comparable<Student>{
public int age;
public String name;
public Student(int age,String name){
this.age = age;
this.name = name;
}
//Comparable在类内实现,对类的侵入性强。并且如果要修改排序规则需要重新修改类内部代码
// == 0 说明相等
// > 0 说明调用方法的对象大于参数对象
// < 0 说名调用方法的对象小于参数对象
@Override
public int compareTo(student o) {
return this.age - o.age;
}
}
3、实现Comparator
class Student {
public int age;
public String name;
public Student(int age,String name){
this.age = age;
this.name = name;
}
}
//Comparator在类外定义比较器,对类的侵入性弱
class stuComparator implements Comparator<Student> {
@Override
public int compare (Student o1,Student o2) {
return o1.age - o2.age;
}
}
public static void mian(String[] args) {
Student[] stus = new Student[]{new Student{15,"王"},new Student{22,"李"},new Student{18,"赵"}};
//Arrays.sort() 默认使用类提供的comparable接口中的compareTo()方法比较
//但是也可以传入自定义的比较器,如果用户传入自定义的比较器就会优先使用自定义的比较器来比较
//即,如果一个类要使用Arrays.sort()方法,要么该类实现comparable接口,要么给该类传入自定义的比较器
Arrays.sort(stus,new stuComparator); //使用自己的比较器
}