作者RockLee (Now of all times)
看板java
标题[问题] Object的hashCode()传回值是unique吗?
时间Fri Jan 13 18:42:27 2012
在 Object 的说明中有一段不是很确定它的意思, 想请教一下:
public int hashCode()
...
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 Java programming
language.)
这段话指的是, 在可行的状况下, Object 的 hashCode() 会传回 unique 的值吗?
例如, 32-bit JVM 中, 至少一个可行的方法是,
籍由传回 object 的 address 达到传回 unique 的值,
所以 32-bit JVM 中 Object 的 hashCode() 传回的是 unique 的值.
这个 unique 传回值通常是 address 但不保证是 address.
但 64-bit JVM 中, 没有可行的方法保证不同 object 可以传回不同的值,
(因为 address 范围超过 integer 范围)
所以 64-bit JVM 中 Object 的 hashCode() 传回的不一定是 unique 的值.
这样的理解正确吗?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.126.30.95
1F:推 james732:Effective Java前几章关於hashCode, equals的讨论可以看 01/13 18:46
2F:→ RockLee:请问您指的是这章吗? 01/13 19:12
4F:→ RockLee:Chapter3.pdf 01/13 19:14
5F:→ RockLee:不好意思我是有看到一些关於hashCode, equals的讨论, 01/13 19:16
6F:→ RockLee:但并没找到哪边讲到Object的hashCode()是如何实作的, 01/13 19:17
7F:→ RockLee:可否更明确地指出在哪边呢? 谢谢~ 01/13 19:18
8F:→ james732:书里没有讲实作方式,只有原则,什麽时候应该相同或不同 01/13 20:11
9F:→ RockLee:了解, 那回到原来问题, 在可行的状况下 (ex. 32-bit JVM), 01/13 20:21
10F:→ RockLee:Object 的 hashCode() 实作是否一定会传回 unique 的值? 01/13 20:22
11F:→ RockLee:有人发现过您用的 JVM 不是传回 unique 的值吗? 01/13 20:23
12F:→ adrianshum:简单一句:不该当hashCode会回传unique值。这非其本意 01/13 22:40
13F:→ RockLee:我了解 hashCode() 的意义, 但这并不是我的问题… 01/13 23:14
14F:→ RockLee:因为 Object 的说明中提到: 01/13 23:17
15F:→ RockLee:However, the programmer should be aware that 01/13 23:19
16F:→ RockLee:producing distinct integer results for unequal objects 01/13 23:21
17F:→ RockLee:may improve the performance of hashtables. 01/13 23:23
18F:→ RockLee:所以我才想确认 Object 原始提供的 hashCode() 实作为何? 01/13 23:24
20F:→ RockLee:lang/Object.html 01/13 23:26
21F:→ qrtt1:那就去翻 source code 啊,翻手册做什麽@@ 01/14 00:19
22F:推 pzyc79:source code只会给你public native int hashCode();这行字 01/14 00:37
23F:→ pzyc79:我想知道这种原生函式的原始码去哪里可以找到@@a; 01/14 00:42
24F:→ RockLee:可是我的问题是, As much as is reasonably practical ... 01/14 00:45
25F:→ RockLee:这段话是否要求所有 JVM 的实作, 在可行的状况下, 01/14 00:47
26F:→ RockLee:Object 的 hashCode() 传回 unique 的值? 01/14 00:48
27F:→ RockLee:似乎不是翻某个 JVM 的 source code 可以解决的... 01/14 00:49
28F:→ pzyc79:就算hashcode真的是unique你也不能把当unique用… 01/14 01:10
29F:推 PsMonkey:太难的事情我不懂,我只想问:你怎麽知道没有被 override 01/14 16:13
30F:→ tkcn:原 po 应该是单纯指 "Object" 这个类别的实体 01/14 16:21
31F:推 ClareQ:不可能是unique,且Object预设hash实作与记忆体位置有关 01/14 16:49
32F:→ RockLee:我问的的确只是"Object"这个类别的hashCode() 01/14 20:27
33F:→ RockLee:为什麽不可能是unique呢? 01/14 20:29
34F:→ RockLee:如果回传记忆体位置至少32-bit JVM就可以达到unique了不是 01/14 20:31
35F:推 PsMonkey:要是我,我也不会跟你保证是 unique... 01/15 13:21