Why can hashCode() return the same value for different objects in Java?

后端 未结 6 1117
粉色の甜心
粉色の甜心 2020-12-01 04:51

A quote from the book I\'m reading Head First Java:

The point is that hashcodes can be the same without necessarily guaranteeing that the objects are

6条回答
  •  长情又很酷
    2020-12-01 05:19

    The hashCode() value can be used to quickly find an object by using the hash code as an address to a hash table bucket where it is stored.

    If multiple objects return the same value from hashCode(), it means that they would be stored in the same bucket. If many objects are stored in the same bucket it means that on average it requires more comparison operations to look up a given object.

    Instead use equals() to compare two objects to see whether they are semantically equal.

提交回复
热议问题