谈谈equlas()和hashcode()方法的之间的关系(为什么重写equlas方法必须要重写hashcode方法)?

1. 首先我们看看对象默认的(Object)的equals方法和hashcode方法

//equals方法比较的是对象的地址
public boolean equals(Object obj) {
	return(this== obj);
}
//hashcode使用的对象的地址生成的一个整数数值
public native int hashCode();

对象在不重写的情况下使用的是Object的equals方法和hashcode方法,从Object类的源码我们知道,默认的equals 判断的是两个对象的引用指向的是不是同一个对象;而hashcode也是根据对象地址生成一个整数数值;

2. hash值是干啥用的?hashcode方法是干啥的?

Java中的hash值主要是用来在散列存储结构中确定对象的存储地址的,提高对象的查询效率。
hashcode方法就是用来高效判断对象是否相等的,一般用在equals前面,hash值相同即判断两对象相等,但是由于不同对象可能拥有相同的hash(hash冲突),因此需要equals再来补充对比

3. hashcode和equals是配套使用的

hashcode速度快,适合查询,但可能由于hash冲突,即不同对象拥有相同的hash,导致判断失败,因此,还要配合equals进一步判断,总结一下

  • equals相等的两个对象,它们的hashCode肯定相等,也就是用equals对比是绝对可靠的;
  • hashCode相等的两个对象,它们的equals不一定相等,也就是hashCode不是绝对可靠的;

4. equals有约定的重写原则

equals的重写原则遵循,equals相等,则hashcode必然相等

如果只重写equals,不重写hashcode方法,就会出现这样的情况,就是两个对象equals方法相等,但是hashcode方法不相等的情况(我们明确规定equals相等,则hashcode必然相等,这就维保了原则)。比如:

public class Employee {
    private String name;
    private int age;

    public Employee() {
    }

    public Employee(String name, int age) {
        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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return age == employee.age &&
                Objects.equals(name, employee.name);
    }

//    @Override
//    public int hashCode() {
//        return Objects.hash(name, age);
//    }
}
 public static void main(String[] args) {
        Employee employee1 = new Employee("张三", 23);
        Employee employee2 = new Employee("张三", 23);

        System.out.println("equals: "+employee1.equals(employee2));
        System.out.println("hashCode: "+employee1.hashCode()+"====="+employee2.hashCode());

    }
equals: true
hashCode: 356573597=====1735600054

可以看到,我们只重写equals方法,不重写hashCode,就会出现equals相等hashCode不相等的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值