How to use an object as a key in a hashmap. If you use an object as key do you need to override equals and hashcode methods for that object?
What happens if we put a key object in a HashMap which exists? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.
If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. This can be done by overriding the hashCode() method. But, you must make sure you are honoring the contract with equals() also.
Custom Key Classes We can conclude that to use a custom class for a key, it is necessary that hashCode() and equals() are implemented correctly. To put it simply, we have to ensure that the hashCode() method returns: the same value for the object as long as the state doesn't change (Internal Consistency)
All instances of Entry class are stored in an array declard as 'transient Entry[] table' . For each key-value to be stored in HashMap, a hash value is calculated using the key's hash code. This hash value is used to calculate the index in the array for storing Entry object.
A simple thumb rule is to use immutable objects as keys in a HashMap
.
because:
If it were mutable, then the hashcode()
value or equals()
condition might change, and you would never be able to retrieve the key from your HashMap
.
More precisely, class fields that are used to compute equals()
and hashcode()
should be immutable!
Now, suppose you create your own class:
equals()
hashcode()
(again, keeping immutability in mind)Remember that if two objects are equal()
, then their hashcode()
should be equal as well!
hashCode() -HashMap provides put(key, value) for storing and get(key) method for retrieving Values from HashMap. When put() method is used to store (Key, Value) pair, HashMap implementation calls hashcode on Key object to calculate a hash that is used to find a bucket where Entry object will be stored. When get() method is used to retrieve value, again key object is used to calculate a hash which is used then to find a bucket where that particular key is stored.
equals() - equals() method is used to compare objects for equality. In case of HashMap key object is used for comparison, also using equals() method Map knows how to handle hashing collision (hashing collision means more than one key having the same hash value, thus assigned to the same bucket. In that case objects are stored in a linked list, refer figure for more clarity. Where hashCode method helps in finding the bucket where that key is stored, equals method helps in finding the right key as there may be more than one key-value pair stored in a single bucket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With