在什么条件下,两个不同的对象可能具有相同的hashcode()值.

问题描述:

我知道的是:-

"int hashCode()返回对象的内存地址为 对象的默认哈希值."

"int hashCode() returns the memory address of the object as the default hash value of the object."

如果引用xy表示两个不同的对象,则表达式 (x.hashCode() == y.hashCode())并不总是错误的

If the references x and y denote two different objects, the expression (x.hashCode() == y.hashCode()) is not always false

所以,我想问问在什么情况下2个不同对象的哈希值相同.

So, I want to ask in which cases the hash values of 2 different objects are same.

您可以在课程中覆盖hashCode.您通常会将其与覆盖equals一起覆盖,因此,如果a.equals(b)为true,则a.hashCode() == b.hashCode()也为true(即使(a == b)为false).

You can override hashCode in your classes. You would usually override it along with overriding equals, so that if a.equals(b) is true, a.hashCode() == b.hashCode() is also true (even if (a == b) is false).

但是,即使a.equals(b)为假,a.hashCode() == b.hashCode()可能仍然为真.

However, even if a.equals(b) is false, a.hashCode() == b.hashCode() may still be true.

如您在Object类的Javadoc中所见:

As you can see in the Javadoc of Object class :

  • 如果根据equals(Object)方法两个对象相等,则必须在两个对象中的每个对象上调用hashCode方法 产生相同的整数结果.
  • 根据java.lang.Object.equals(java.lang.Object)方法,如果两个对象不相等,则不需要调用 两个对象中每个对象的hashCode方法必须产生不同的 整数结果.但是,程序员应注意 为不相等的对象产生不同的整数结果可能会改善 哈希表的性能.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.