Issue
I was reading about how hashmap works. I was reading through the "What will happen if two different objects have same hashcode".
According to it if two objects has same hashcode both will be stored in LinkedList
but as far as I know if two hashcode then previous one will get overwritten with new one (correct me if I am wrong).
Can someone please put more light on how hashmap use object as key internally and what will happen if two objects has same hashcode and how both objects will be fetched with get()
?
Solution
No, the first one isn't overwritten just because the second one has the same hashCode
.
It will be overwritten only if it is also equal (as said by equals
). If not, both values will be kept in the linked list.
When fetching a key, all nodes with the same hashCode
will be compared to the provided key until one is equal then its value will be returned (using the equals
method).
If no key in the map is equal, you'll get null
.
The only problem you have if many objects have the same hashCode (or more precisely the same hashCode modulo the size of the internal Entry[] table
) is that the linked list will always be read, which is slower (and defeats the purpose of any hash table). That's why it's important when designing a hashcode
method to ensure the generated integers are well distributed.
Answered By - Denys Séguret
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)