How hashCode() method in Object class is implemented? [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-05 09:11:38

It's implemented in the native code. As for implementation, it's a bit more tricky - you can alter default implementation. If you look at the "Open JDK" sources you will see the following options:

-XX:hashCode=n (from 0 to 5).

  • 0 – Park-Miller RNG (default)
  • 1 – function of address and some global state
  • 2 – const 1
  • 3 – sequenatial counter
  • 4 – address of an object
  • 5 – thread specific xor-shift

You can find a detailed implmenetation here: http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/tip/src/share/vm/runtime/synchronizer.cpp

Consider source code and comments of static inline intptr_t get_next_hash() function.

The native keyword indicates that it has been implemented in native code (the JVM).

If you see the declaration of hashcode

public native int hashCode();

native in declaration indicates that it is implemented natively in jvm code.

Mike Perrenoud

Where is the implementation part?

It's implemented by the framework already. Please see the documentation.

If there is no implementation how does the hashCode() method return me a result?

However, if you create a custom type you are responsible for generating an int value that is a good representation of the objects current state. Here is a good example of that.

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