hashCode
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.
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 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.
equal
For any non-null reference value x, x.equals(null) should return false.
public boolean equals(Object obj) {
return (this == obj);
}
toString
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
本文深入探讨了Java中hashCode方法的实现原则,强调了在多次调用同一对象时需返回一致整数的重要性,以及与equals方法的关系。指出hashCode在不同执行间不必保持一致,但相等对象必须产生相同结果。同时,不相等对象产生不同整数可提升哈希表性能。
4736

被折叠的 条评论
为什么被折叠?



