What happens if two different objects have the same hashcode?

后端 未结 5 1498
余生分开走
余生分开走 2020-12-28 17:23

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?

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 17:52

    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.

提交回复
热议问题