1

If object1 and object2 are two different types of objects but implement the same interface I, and we assume object1 and object2 have same hash code.

There is a HashMap<I, String>.

So we can call put(object1, "some string") and put(object2, "some string") by that hash map.

My understanding is:

  1. For put() function, the position of the object in hash map depends on the hash code of the key object. After the object1 put into the map first, then we try to put object2. It will find the position has been occupied by object1 already. So the object2 will be put into object1's next position.
  2. For get() function, if we call get(object2), it will find object1 first, and find object1 != object2, then it will continue to compare the next element of object1 until find the same object with object2

Just want to know if I am correct? Or any supplement information within this mechanism.

yjasrc
  • 503
  • 1
  • 4
  • 15

3 Answers3

3

This would be considered to be a hash collision. Most likely the hash implementation will find the same bucket and then walk down each entry until equals() returns true for the key. All reasonable hash implementations have to account for the possibility of collisions, but these degrade the hashing performance.

seand
  • 5,168
  • 1
  • 24
  • 37
1

Refer these links, 1.how HashMap works in Java and 2.how HashMap works in Java

Visruth
  • 3,430
  • 35
  • 48
0

Yes you are right with your understanding. Refer Effective Java for even better understanding.

aryann
  • 909
  • 5
  • 11