5

Possible Duplicate:
What’s the implementation of hashCode in java Object?

While I was browsing through the Object class, I found that there is only a declaration of the hashCode() method. Where is the implementation part? If there is no implementation how does the hashCode() method return me a result?

Community
  • 1
  • 1
Nihal Sharma
  • 2,397
  • 11
  • 41
  • 57

4 Answers4

11

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.

Andrey Taptunov
  • 9,367
  • 5
  • 31
  • 44
7

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

akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
  • thanks, but how and who gets this hashcode value and how is it returned? A little insight please!! – Nihal Sharma Jan 25 '13 at 12:28
  • 3
    That would involve looking into the code of the JVM itself and knowing how JNI (Java Native Interface) implementations of methods are bound to their Java definitions. I believe the actual value is not consistent among implementations of the JVM. If you need to rely on the actual value, override the method to conform to your own needs. – akaIDIOT Jan 25 '13 at 12:30
  • +1. and I don't think there is a spec regarding the actual value of the hashcode and manner of its calculation. (But of course, it needs to be internally consistent in the same way as any other hashCode). – Thilo Jan 25 '13 at 12:31
5

If you see the declaration of hashcode

public native int hashCode();

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

MoveFast
  • 3,011
  • 2
  • 27
  • 53
0

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.

Community
  • 1
  • 1
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232