identityHashCode与Hashcode

819 阅读1分钟

hashcode

java类都是继承自java.lang.Object类,同时继续了Object类的hashCode方法

public native int hashCode();

hashCode方法可以根据对象的内存地址算出来一个int数字,代表了该对象在内存中的存储位置。

有些类重写了hashcode,如String, 计算方式如下:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

可以看出,当String的值相同时,计算出的hashcode值是相同的。

identityHashCode

是由java.lang.System类提供了一个静态方法

public static native int identityHashCode(Object x);

identityHashCode根据对象的内存地址来计算hashcode,不管对象是不是重写了hashcode方法。

代码展示