What is the default implementation of `hashCode`? [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-17 17:53:21

问题


If one does not override the hashCode method, what is the default implementation of hashCode ?


回答1:


Then this class inherits hashCode from one of its ancestors. If non of them overrides it, then Object.hashCode is used.

From the docs:

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.)

So default implementation is JVM-specific




回答2:


By default, methods that are not overriden are inherited from Object.

If you look at that method's documentation, the return values are "[...] distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer [...])". The method in java.lang.Object is declared as native, which means the implementation is provided by the JVM and may vary depending on your runtime environment.

A small example:

Object o1 = new Object();
Object o2 = new Object();
System.out.println(o1.hashCode());
System.out.println(o2.hashCode());

prints (using my jdk6):

1660187542
516992923

A Hex representation of the hashCode() value is used in the default implementation of toString() by the way: Running System.out.println(o1) prints something like

java.lang.Object@7a5e1077



回答3:


Object.hashcode() is a native method.

public native int hashCode();

That means it's implemented in platform specific code and is exposed as a native method.

code for the same will be a compiled code and not available withing JDK

this existing question might provide more info.



来源:https://stackoverflow.com/questions/15130764/what-is-the-default-implementation-of-hashcode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!