简体   繁体   中英

Consequences of different hashcodes but same equals for two java objects

I understand that we should have same hashcodes incase equals are same for two java objects, but just wanted to understand if hashcodes are not same but equals returns true , what would be the consequences with respect to collections like HashMap, HashSet etc.

Would it only impact the performance or will it impact the behavior/functionality of those collection classes.

It would break the functionality. If you are looking for an object in a hashmap or hashset, it is using the hash code in order to find it. If the hash code is not consistent, it probably will not be able to find it.

The most basic requirement of a hash code is that two equal objects must have the same hash code. Everything else is secondary.

The consequences will be unexpected behavior.

If a.equals(b) == true but a.hashCode()!=b.hashCode() , set.add(a) followed by set.contains(b) will most likely return false (assuming set is a HashSet ), even though according to equals it should return true . (the reason it's most likely and not a certainty is that two different hash codes still have a chance of being mapped to the same bucket of the HashSet/HashMap , in which case you can still get true ).

If two objects are equal, their hashcode will always return same value.

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Please read this

Let's call the objects o1 and o2 where o1.equals(o2) but o1.hashCode() != o2.hashCode()

Consider the following:

Map map = new HashMap();
Set set = new HashSet();
map.put(o1, "foo");
set.add(o1);

The following assertions would fail

Assert.assertTrue(map.containsKey(o2));
Assert.assertTrue(set.contains(o2));

It will miss the bucket during fetch. HashMap is designed to store huge data with fetch time as O(1) in best possible scenario. To do this it stores key/values marked against hashcode(which we generally refer as bucket). This is called hashing technology. So you stored it in hashmap with hashcode number, say 100 and now you are trying to fetch the object with different hashcode (say 200)(ie looking inside different bucket). So even though your object is inside hashmap, it will not be able to retrieve it because it will try to find in different bucket (ie 200). That is the reason we should have same hashcodes incase equals are same for two java objects

HashMap/HashSet is meant to help you find what the target object in the collections. If two equal objects have different hashcodes, you are unlikely to find the object in the hash bucket.

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