In Java, why must equals() and hashCode() be consistent?

后端 未结 6 1133
挽巷
挽巷 2020-11-28 13:13

If I override either method on a class, it must make sure that if A.equals(B) == true then A.hashCode() == B.hashCode must also be true.

Can

6条回答
  •  萌比男神i
    2020-11-28 13:54

    It's exactly because of hash tables.

    Because of the possibility of hash code collisions, hash tables need to check identity as well, otherwise the table can't determine if it found the object it was looking for, or one with the same hash code. So every get() in a hash table calls key.equals(potentialMatch) before returning a value.

    If equals() and hashCode() are inconsistent you can get very inconsistent behavior. Say for two objects, a and b, a.equals(b) returns true, but a.hashCode() != b.hashCode(). Insert a and a HashSet will return false for .contains(b), but a List created from that set will return true (because the list doesn't use hash codes).

    HashSet set = new HashSet();
    set.add(a);
    set.contains(b); // false
    new ArrayList(set).contains(b); // true
    

    Obviously, that could be bad.

提交回复
热议问题