为什么重写equals()方法就要重写hashcode()?

首先我们只重写equals()方法

public class Student {
    private String name;
    private  int age;
    private  String QQ;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return age == student.age &&
            Objects.equals(name, student.name) &&
            Objects.equals(QQ, student.QQ);
}

看我们的测试类

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        Student student2 = new Student();
        System.out.println(student.equals(student2));    //true
        System.out.println(student.hashCode());            //356573597
        System.out.println(student2.hashCode());           //1735600054 
        HashMap<Student, String> map = new HashMap<>();
        map.put(student,"123");
        map.put(student2,"456");
        System.out.println(map.get(student));
        System.out.println(map.get(student2));

    }
}

依次输出

true
356573597 student 的hashcode值
1735600054 student 2的hashcode值
123
456

是否出现矛盾???
用equals比较说明对象相同,但是在HashMap中却以不同的对象存储(没有重写hascode值,两个hascode值,在他看来就是两个对象)。
到底这两个对象相等不相等????
说明必须重写hashCode()的重要性,

接下来重写重写equals方法和hashCode方法,再比较

public class Student {

private String name;
private  int age;
private  String QQ;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return age == student.age &&
            Objects.equals(name, student.name) &&
            Objects.equals(QQ, student.QQ);
}

@Override
public int hashCode() {

    return Objects.hash(name, age, QQ);
}

}

测试类

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        Student student2 = new Student();
        System.out.println(student.equals(student2));   //true
        System.out.println(student.hashCode());          // 29791   
        System.out.println(student2.hashCode());       // 29791   
        HashMap<Student, String> map = new HashMap<>();
        map.put(student,"123");
        map.put(student2,"456");
        System.out.println(map.get(student));   //456
        System.out.println(map.get(student2)); //456

    }
}

依次输出
true
29791 //相同的对象
29791
456 //说明以一个值key存储,相同的值
456

Equals()和hashcode()
重写equals就必须重写hashcode
1、如果两个对象equals,他们的hashcode一定相等。
2、如果两个对象不equals,他们的hashcode有可能相等。
3、如果两个对象hashcode相等,他们不一定equals。
4、如果两个对象hashcode不相等,他们一定不equals。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值