It is my understanding that two unequal objects can have the same hashcode. How would this be handled when adding or retrieving from a HashMap java?
It is perfectly legal for two objects to have the same hashcode. If two objects are equal (using the equals() method) then they have the same hashcode. If two objects are not equal then they cannot have the same hashcode.
Since, hashmap searches key/value pair based on hashcode of key. Hashmap will find 209 hashcode for key "b". Since, same hashcode is found for key "a", Hashmap may return value "aValue" instead of expected value "bValue". So, here is my question, I want to retrieve value associated with key.
If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.
When two key return same hashcode, they end up in the same bucket. Now, in order to find the correct value, you used keys. equals() method to compare with key stored in each Entry of linked list there. Remember to point out keys.
They will just be added to the same bucket and equals()
will be used to distinguish them.
Each bucket can contain a list of objects with the same hash code.
In theory you can return the same integer as a hash code for any object of given class, but that would mean that you loose all performance benefits of the hash map and, in effect, will store objects in a list.
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