- Javadoc:
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.
- 中文解释:
返回对象的哈希值,在该对象的类没有重写了hashCode()方法的情况下,与hashCode()方法返回的哈希值相同。另外,null的哈希值为零。在hashCode()方法被重写的情况下,就不能根据hashCode()方法来判断两个变量是否引用了同一个对象,但可以根据System.identityHashCode(Object x)方法来判断两个变量是否引用了同一个对象。
- 可参考以下测试用例:
public class HashcodeTest {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = p1;
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
System.out.println(System.identityHashCode(p1));
System.out.println(System.identityHashCode(p2));
}
}
class Person {
static int i = 0;
/*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return i++;
}
}
输出结果:p1.hashCode()和p2.hashCode()的值不一样,但System.identityHashCode(p1)和System.identityHashCode(p2)的值相同,可据此判断p1和p2引用的是同一个对象。