-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;
}
}
@SotiriosDelimanolis谢谢,我重述了它。 – Jack 2014-10-07 01:12:12
如果对象相等,但hashCode不同,则表示您没有正确覆盖hashCode。这是一种迂回的说法,“如果你重写equals,你必须重写hashCode”。请参阅Joshua Bloch的“Effective Java”第3章。 – duffymo 2014-10-07 01:12:14
我对这些语句的理解是[1]如果您的对象是相同的(对象基本上是某种状态),[2]如果2个对象在等于时返回true (),那么他们的hashcode也必须是相同的[3]如果两个对象不是equals()彼此,那么不一定你必须返回不同的hashcode(因为我相信hashcode的想法是快速的返回一些给定散列函数的对象,但当然没有散列函数是完美的,所以可能会发生碰撞,所以没关系) – Leo 2014-10-07 01:24:55