Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if two different objects have the same hashcode?

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?

like image 656
Joey Avatar asked Jun 25 '12 18:06

Joey


People also ask

Can two different objects have the same Hashcode?

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.

What happens if two keys have the same Hashcode in HashMap?

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.

Can two different strings have same Hashcode?

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.

What will happen if Hashcode returns same value?

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.


1 Answers

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.

like image 129
Alex Gitelman Avatar answered Oct 06 '22 04:10

Alex Gitelman