问题描述
后端的Object.hashCode()
和System.identityHashCode()
如何工作?
假设尚未覆盖,则该Object.hashCode()
方法只需调用即可System.identityHashCode(this)
。
的确切行为System.identityHashCode(Object)
取决于JVM实现。(在最近的Hotspot JVM上的实际实现是相当聪明的,但是我离题了。)
是否identityHashCode()
返回对象的引用?
否。它返回int,而an int不能保存引用。
返回的整数identityHashCode
可能与对象的(a)机器地址有关,或者可能不是1。identityHashCode()
保证返回的值在对象的生存期内不会改变。这意味着,如果GC(在identityHashCode()
调用之后)重定位对象,则它不能使用新的对象地址作为身份哈希码。
hashCode()是否取决于?对象? ==运算符的后端工作方式。
这没有道理。Java中没有? ==
或?==
运算符。
hashCode()和identityHashCode()有什么区别?
以上已部分解释。其他差异包括:
-
该
hashcode()
方法是非最终实例方法,并且在覆盖的任何类中都应覆盖此equals(Object)
方法。相反,identityHashCode(Object)
是一种static
方法,因此不能被覆盖。 -
该
identityHashCode(Object)
方法为你提供了一个对象的标识符,该标识符在理论上可以用于哈希和哈希表以外的其他用途。(不幸的是,它不是一个独特的标识符,但被保证为对象的生命周期永远不会改变。)
解决方法
如何做Object.hashCode()
和System.identityHashCode()
工作在后端?是否identityHashCode()
返回对象的引用?是否hashCode()
取决于?对象的?==操作员如何在后端工作。
hashCode()
和之间有什么区别identityHashCode()
?