通过在对象相等的情况下使用不同的哈希码,不确定Oracle意味着什么?

时间:2014-10-07 01:09:16

标签: java equals hashcode

我没有得到Oracle的含义如下:在我看来,第一个和第二个是相同的,两个相等对象的哈希码应该总是相同的!并且对于最后一个是否意味着,让我们在下面的代码中更改其他类中的prime的值?

1) Whenever it is invoked on the same object more than once during an 
   execution of a Java application, the hashCode method must consistently return 
   the same integer, provided no information used in equals comparisons on 
   the object is modified. This integer need not remain consistent from 
   one execution of an application to another execution of the same application.

2) 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.

3) It is not required that if two objects are unequal according to the 
   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 hash tables. 

mycode的

public class Derived {
    private int myVar;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + myVar;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Derived other = (Derived) obj;
        if (myVar != other.myVar)
            return false;
        return true;
    }

}

1 个答案:

答案 0 :(得分:0)

为了使对象在散列表中正常运行,hashCode()函数返回一致值非常重要。特别是2个逻辑上相等的值必须具有相同的hashCode(),否则您将看到flakiness。

原因是哈希表通常的工作方式。常见的实现是指向“桶”的单个指针数组。要查找对象,调用hashCode(),然后采用模数来查找此数组中的索引。一旦我们找到索引,我们就会在桶中查找对象,可能会测试==和equals()直到匹配。

假设一个对象'foo'在表中,带有hashCode()1234。现在我们搜索一个声称为'foo'的对象,但它的hashCode()是不同的。很可能我们会查看错误的桶,因此即使两个对象都返回真正的equals(),我们也找不到匹配。同样,该表假定哈希码是稳定的(不可变的)。