hashCode和identityHashCode的区别你知道吗?
轉(zhuǎn)載自?hashCode和identityHashCode的區(qū)別你知道嗎?
hashCode
關(guān)于hashCode參考之前的文章,點(diǎn)擊參考之前文章。
identityHashCode
identityHashCode是System里面提供的本地方法,java.lang.System#identityHashCode。
/*** 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.** @param x object for which the hashCode is to be calculated* @return ?the hashCode* @since ? JDK1.1*/ public static native int identityHashCode(Object x);identityHashCode和hashCode的區(qū)別是,identityHashCode會(huì)返回對(duì)象的hashCode,而不管對(duì)象是否重寫了hashCode方法。
示例
public static void main(String[] args) {String str1 = new String("abc");String str2 = new String("abc");System.out.println("str1 hashCode: " + str1.hashCode());System.out.println("str2 hashCode: " + str2.hashCode());System.out.println("str1 identityHashCode: " + System.identityHashCode(str1));System.out.println("str2 identityHashCode: " + System.identityHashCode(str2)); ? ?User user = new User("test", 1);System.out.println("user hashCode: " + user.hashCode());System.out.println("user identityHashCode: " + System.identityHashCode(user)); }輸出結(jié)果:
str1 hashCode: 96354 str2 hashCode: 96354 str1 identityHashCode: 1173230247 str2 identityHashCode: 856419764 user hashCode: 621009875 user identityHashCode: 621009875結(jié)果分析:
1、str1和str2的hashCode是相同的,是因?yàn)镾tring類重寫了hashCode方法,它根據(jù)String的值來確定hashCode的值,所以只要值一樣,hashCode就會(huì)一樣。
2、str1和str2的identityHashCode不一樣,雖然String重寫了hashCode方法,identityHashCode永遠(yuǎn)返回根據(jù)對(duì)象物理內(nèi)存地址產(chǎn)生的hash值,所以每個(gè)String對(duì)象的物理地址不一樣,identityHashCode也會(huì)不一樣。
3、User對(duì)象沒重寫hashCode方法,所以hashCode和identityHashCode返回的值一樣。
結(jié)論
hashCode方法可以被重寫并返回重寫后的值,identityHashCode會(huì)返回對(duì)象的hash值而不管對(duì)象是否重寫了hashCode方法。
總結(jié)
以上是生活随笔為你收集整理的hashCode和identityHashCode的区别你知道吗?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JDK8新特性之函数式接口
- 下一篇: IntegerCache的妙用和陷阱