How does a Java HashMap handle different objects with the same hash code?

As per my understanding I think:

  1. It is perfectly legal for two objects to have the same hashcode.
  2. If two objects are equal (using the equals() method) then they have the same hashcode.
  3. If two objects are not equal then they cannot have the same hashcode

Am I correct?

Now if am correct, I have the following question:
The HashMap internally uses the hashcode of the object. So if two objects can have the same hashcode, then how can the HashMap track which key it uses?

Can someone explain how the HashMap internally uses the hashcode of the object?

15 Answers
15

Leave a Comment