A couple days ago a coworker and I were working on a piece of code that at first seemed
like a mystery to us. We were working with a set. Every attempt at removing the value from
the set resulted in
false
. After hours of looking at the code we discovered that the value was
changing, which was the source of our problem. the Actual problem was the new
Hashcode
for the object doesn't match the Hashcode
the set used to store the
value.
Source:
Immutable
Source Code With Problem and Results
Key Points to Remember
Hash set
is backed byHash Map
Hash Map
uses hashing algorithm to store object as a Key value for the Map.
When hash value is Calculated for the Hash Map Objects
- Hash value for an object is calculated at the time, we add it into Hash Map as a key, and store this value in the Hash Map as a hashing bucket for this key.
- Any time we try to retrieve values from the Map against the key it does following operations:
- Calculate hash value from the object
- Find the bucket from the hash map for the objects hash value.
- If bucket contains multiple object it uses equals method to compare two objects and return proper key value.
- If bucket only contain one object it return this value directly without any another compare.
Drawbacks of The Mutable Objects
- If object is updated via any other thread or method the behavior will be unexpected.
- We get unexpected behavior because Hash value for object will be changed even though user is changing same Object which is stored to Map.
- As the hash value changes for the object, we are not able to find the hashing bucket for this object.
- Once object changes some methods start giving unpredictable results.
- Hash Set
remove
method (Object cant be removed). - Hash Set
add
method (Object added again). - Hash Set
contains
method (Returns false for the object) - Hash Map
put
(Key will be added again) - Hash Map
remove
(Object cant be removed) - Hash Map
contains
(Returns false for the object)
Key in Hash Map should always be Immutable
4 Comments
or always implement hashCode and equals method for classes whose object are going to be key in "hashed" collections by making sure that the hashCode()never changes based on change of other instance variables.
ReplyDelete+1
DeleteHash Code should not depend on state of the object
ReplyDeleteyou have changed the P1, P2 and P3 object values as null, and insert only P1 in set.
ReplyDeleteand then you tried to remove these objects from set, but only the new instance of p1 got deleted or removed. Because pointer holds the reference of updated objects, and others are not present in set.
Post a Comment