我不是在谈论String类或任何其他覆盖了哈希码的类。假设我只是创建了一个Object
类的新对象,那么hashcode()
或者更确切地说,在任何情况下,identityHashCode(Object x)
会返回该对象的内存地址吗?
我不是在谈论String类或任何其他覆盖了哈希码的类。假设我只是创建了一个Object
类的新对象,那么hashcode()
或者更确切地说,在任何情况下,identityHashCode(Object x)
会返回该对象的内存地址吗?
尽管合理可行,Object类定义的hashCode方法确实会为不同的对象返回不同的整数。(通常通过将对象的内部地址转换为整数来实现,但JavaTM编程语言并不要求使用这种实现技术。)
hashcode
是一个整数,很可能计算机的地址空间比可用的整数要大,并且将内部地址转换为整数并不一定是双射关系。 - assylias(jnit) (void*) address
了,实际的实现在对象头中存储了一次性随机数。 - bestsss您可以通过查看随JDK提供的源代码来进行检查。
我的java.lang.Object
将hashCode
显示为本地方法。这是javadoc文档。
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables such as those provided by
* <code>java.util.Hashtable</code>.
* <p>
* The general contract of <code>hashCode</code> is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the <tt>hashCode</tt> method
* must consistently return the same integer, provided no information
* used in <tt>equals</tt> 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.
* <li>If two objects are equal according to the <tt>equals(Object)</tt>
* method, then calling the <code>hashCode</code> method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the <tt>hashCode</tt> 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 hashtables.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class <tt>Object</tt> does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java<font size="-2"><sup>TM</sup></font> programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.util.Hashtable
*/
public native int hashCode();
正如文档中关于 Object.hashCode() 的说明所述:
在合理的情况下,Object类定义的hashCode方法确实会为不同的对象返回不同的整数。(通常这是通过将对象的内部地址转换为整数来实现的,但JavaTM编程语言不要求采用此实现技术。)
因此,Java语言对于Object类的哈希码没有要求必须返回对象的内存地址,因此您不应该依赖于此。
identityHashCode()
中看到更多的模式。(试一试,创建100个对象,打印它们的哈希码并尝试找到一个模式)。 - Joachim Sauer