2014-10-07 38 views
-1

我没有得到什么Oracle表示以下内容:在我看来,第一个和第二个是相同的,两个相同的对象的哈希码应该始终是相同的!对于最后一个这是否意味着,让我们在下面的代码中改变其他类中素数的值?不确定Oracle通过在对象相同的情况下拥有不同的哈希码是什么意思?

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; 
    } 

} 
+0

@SotiriosDelimanolis谢谢,我重述了它。 – Jack 2014-10-07 01:12:12

+0

如果对象相等,但hashCode不同,则表示您没有正确覆盖hashCode。这是一种迂回的说法,“如果你重写equals,你必须重写hashCode”。请参阅Joshua Bloch的“Effective Java”第3章。 – duffymo 2014-10-07 01:12:14

+0

我对这些语句的理解是[1]如果您的对象是相同的(对象基本上是某种状态),[2]如果2个对象在等于时返回true (),那么他们的hashcode也必须是相同的[3]如果两个对象不是equals()彼此,那么不一定你必须返回不同的hashcode(因为我相信hashcode的想法是快速的返回一些给定散列函数的对象,但当然没有散列函数是完美的,所以可能会发生碰撞,所以没关系) – Leo 2014-10-07 01:24:55

回答

0

为了一个目的哈希表中正常工作,为的hashCode()函数返回的值一致是很重要的。特别是2个逻辑上相同的值必须具有相同的hashCode(),否则你会看到片状。

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

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

相关问题