equals,hashCode和Comparable、Comparator

对象比较的三种方法

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);  //使用自己的比较器
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值