`hashCode`的默认实现是什么?

Joh*_*ood 54 java hashcode

如果没有覆盖该hashCode方法,那么默认实现是hashCode什么?

def*_*ale 49

然后这个类继承hashCode自它的一个祖先.如果不覆盖它,则使用Object.hashCode.

来自文档:

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

因此,默认实现是特定于JVM的

  • @JohnThreepwood,这是一个实现细节,您需要为此解决您的 JVM 文档。 (2认同)
  • http://stackoverflow.com/a/32454673/6785908 (2认同)

f1s*_*1sh 15

默认情况下,继承未覆盖的方法Object.

如果查看该方法的文档,返回值为" [...] distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer [...])".方法in java.lang.Object声明为native,这意味着实现由JVM提供,并且可能根据您的运行时环境而有所不同.

一个小例子:

Object o1 = new Object();
Object o2 = new Object();
System.out.println(o1.hashCode());
System.out.println(o2.hashCode());
Run Code Online (Sandbox Code Playgroud)

打印(使用我的jdk6):

1660187542
516992923
Run Code Online (Sandbox Code Playgroud)

hashCode()在默认实现中使用值的十六进制表示toString():运行System.out.println(o1)打印类似的东西

java.lang.Object@7a5e1077
Run Code Online (Sandbox Code Playgroud)


The*_*bit 5

Object.hashcode() 是本机方法。

public native int hashCode();

这意味着它是在特定于平台的代码中实现的,并作为本机方法公开。

相同的代码将是编译后的代码,并且在 JDK 中不可用

这个现有的问题可能会提供更多信息。