Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

hash - how is hashCode() implemented in Java

How is hashCode() implemented?

My assumption is that it uses the object memory location as the initial number (the seed) on which it runs the hash function. However, this is not the case.

I've also looked at Hash : How does it work internally? but it does not answer my question.

Yes I could download the SDK, but before I do that and look at the code, perhaps someone else already has knowledge of it.

Thanks :)

EDIT: I know it should be overridden and such, so please try to stay on topic :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, no, no. All answers in this thread are wrong or at least only partially correct.

First: Object.hashCode() is a native method, so its implementation depends solely on the JVM. It may vary between HotSpot and other VM implementations like JRockit or IBM J9.

If you are asking:

how is hashCode() implemented in Java?

Then the answer is: it depends on which VM you are using.

Assuming that you are using Oracle's default JVM—which is HotSpot, then I can tell you that HotSpot has six hashCode() implementations. You can choose it using the -XX:hashCode=n flag running JVM via command line, where n can be:

0 – Park-Miller RNG (default)
1 – f(address, global_statement)
2 – constant 1
3 – Serial counter
4 – Object address
5 – Thread-local Xorshift

The above is copied from this post.

And if you dig a little bit around in the HotSpot source code, you may find below snippet:

if (hashCode == 0) {
  value = os::random();
} else {
  ...

os::random() is just the implementation of the Park-Miller Pseudo Random Generator algorithm.

That's all. There isn't any notion of memory address. Although two other implementations, 1 and 4, use an object's memory address, the default one doesn't use it.
The notion that Object.hashCode() is based on the object's address is largely a historic artefact - it is no longer true.


I know that inside Object#hashCode() JavaDoc we can read:

(...) this is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java? programming language.

But it is obsolete and misleading.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[1] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...