hashcode是否返回内存地址?

可能重复:
什么是对象哈希码
hashCode()和identityHashCode()如何在后端工作?

我不是在讨论String类或其他重写hashcode的类。 假如我只是创建一个Object类的新对象,那么hashcode()或者在任何情况下都是true, identityHashCode(Object x)返回该identityHashCode(Object x)的内存地址?

不必要。 从文档 (强调我的):

尽可能合理,Object类定义的hashCode方法确实为不同的对象返回不同的整数。 (这通常通过将对象的内部地址转换为整数来实现但JavaTM编程语言不需要此实现技术 。)

不,HashCode()函数返回一个整数。 如果尚未为对象定义HashCode()函数,Java可以将对象的内存地址转码为整数并返回该值。

您可以随时查看JDK附带的源代码进行检查。

我的java.lang.Object hashCode显示为本机方法。 这是javadocs。

 /** * Returns a hash code value for the object. This method is * supported for the benefit of hashtables such as those provided by * java.util.Hashtable. * 

* The general contract of hashCode is: *

    *
  • Whenever it is invoked on the same object more than once during * an execution of a Java application, the hashCode method * must consistently return the same integer, provided no information * used in equals 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. *
  • If two objects are equal according to the equals(Object) * method, then calling the hashCode method on each of * the two objects must produce the same integer result. *
  • It is not required that if two objects are unequal * according to the {@link java.lang.Object#equals(java.lang.Object)} * method, then calling the hashCode 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. *
*

* As much as is reasonably practical, the hashCode method defined by * class Object 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 * JavaTM 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类的哈希码返回对象的内存地址,因此您不应该依赖于此。