关于java:为什么重写equals必须重写hashCode

2次阅读

共计 2001 个字符,预计需要花费 6 分钟才能阅读完成。

equals 常见面试题

在开始聊之前,咱们先看几个常见的面试题,看看你能不能都答复上来。

  • 1、equals 和 == 有什么区别?
  • 2、hashcode 相等的两个对象肯定 == 相等吗?equals 相等吗?
  • 3、两个对象用 equals 比拟相等,那它们的 hashcode 相等吗?

如果咱们不重写 equals 和 hashcode,那么它应用的是 Object 办法的实现。咱们先简略看一下

public boolean equals(Object obj) {return (this == obj);
}
public static int hashCode(Object o) {return o != null ? o.hashCode() : 0;
}

为什么要重写 equals

通过以上代码能够看出,Object 提供的 equals 在进行比拟的时候,并不是进行值比拟,而是内存地址的比拟。由此能够通晓,要应用 equals 对对象进行比拟,那么就必须进行重写 equals。

重写 equals 不重写 hashCode 会存在什么问题

咱们先看上面这段话

每个笼罩了 equals 办法的类中,必须笼罩 hashCode。如果不这么做,就违反了 hashCode 的通用约定,也就是下面正文中所说的。进而导致该类无奈联合所以与散列的汇合一起失常运作,这里指的是 HashMap、HashSet、HashTable、ConcurrentHashMap。
来自 Effective Java 第三版

论断: 如果重写 equals 不重写 hashCode 它与散列汇合无奈失常工作。

既然这样那咱们就拿咱们最相熟的 HashMap 来进行演示推导吧。咱们晓得 HashMap 中的 key 是不能反复的,如果反复增加,后增加的会笼罩后面的内容。那么咱们看看 HashMap 是如何来确定 key 的唯一性的。

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

查看代码发现,它是通过计算 Map key 的 hashCode 值来确定在链表中的存储地位的。那么这样就能够揣测出,如果咱们重写了 equals 然而没重写 hashCode,那么可能存在元素反复的矛盾状况。

上面咱们来演示一下

public class Employee {

private String name;

private Integer age;

public Employee(String name, Integer age) {
    this.name = name;
    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 Objects.equals(name, employee.name) &&
            Objects.equals(age, employee.age);
}

/*@Override
public int hashCode() {return Objects.hash(name, age);
}*/
}
public static void main(String[] args) {Employee employee1 = new Employee("冰峰", 20);
    Employee employee2 = new Employee("冰峰", 22);
    Employee employee3 = new Employee("冰峰", 20);

    HashMap<Employee, Object> map = new HashMap<>();

    map.put(employee1, "1");
    map.put(employee2, "1");
    map.put(employee3, "1");

    System.out.println("equals:" + employee1.equals(employee3));
    System.out.println("hashCode:" + (employee1.hashCode() == employee3.hashCode()));
    System.out.println(JSONObject.toJSONString(map));
}

按失常状况来揣测,map 中只存在两个元素,employee2 和 employee3。

执行后果

呈现这种问题的起因就是因为没有重写 hashCode,导致 map 在计算 key 的 hash 值的时候,绝对值雷同的对象计算除了不统一的 hash 值。


接下来咱们关上 hashCode 的正文代码,看看执行后果

总结

如果重写了 equals 就必须重写 hashCode,如果不重写将引起与散列汇合(HashMap、HashSet、HashTable、ConcurrentHashMap)的抵触。

正文完
 0