简体   繁体   中英

General contract for object comparision : equals() and hashCode()

There is a point in general contract of equals method, which says if You has defined equals() method then You should also define hashCode() method. And if o1.equals(o2) then this is must o1.hashCode() == o2.hashCode() .

So my question is what if I break this contract? Where can bring fails the situation when o1.equals(o2) but o1.hashCode != o2.hashCode() ?

它将导致基于散列的数据结构中的意外行为,例如: HashMap读取HashTable的工作原理

HashMap/HashTable/HashSet/etc will put your object into one of several buckets based on its hashCode , and then check to see if any other objects already in that bucket are equal .

Because these classes assume the equals/hashCode contract, they won't check for equality against objects in other buckets. After all, any object in another bucket must have a different hashCode, and thus (by the contract) cannot be equal to the object in quesiton. If two objects are equal but have different hash codes, they could end up in different buckets, in which case the HashMap/Table/Set/etc won't have a chance to compare them.

So, you could end up with a Set that contains two objects which are equal -- which it's not supposed to do; or a Map that contains two values for the same one key (since the buckets are by key); or a Map where you can't look up a key (since the lookup checks both the hash code and equality); or any number of similar bugs.

If you break the contract, your objects won't work with hash-based containers (and anything else that uses hashCode() and relies on its contract).

The basic intuition is as follows: to see whether two objects are the same, the container could call hashCode() on both, and compare the results. If the hash codes are different, the container is allowed to short-circuit by assuming that the two objects are not equal.

To give a specific example, if o1.equals(o2) but o1.hashCode() != o2.hashCode() , you'll likely be able to insert both objects into a HashMap (which is meant to store unique objects).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM