看板 java 關於我們 聯絡資訊
在 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
james732:Effective Java前幾章關於hashCode, equals的討論可以看 01/13 18:46
RockLee:請問您指的是這章嗎? 01/13 19:12
RockLee:Chapter3.pdf 01/13 19:14
RockLee:不好意思我是有看到一些關於hashCode, equals的討論, 01/13 19:16
RockLee:但並沒找到哪邊講到Object的hashCode()是如何實作的, 01/13 19:17
RockLee:可否更明確地指出在哪邊呢? 謝謝~ 01/13 19:18
james732:書裡沒有講實作方式,只有原則,什麼時候應該相同或不同 01/13 20:11
RockLee:了解, 那回到原來問題, 在可行的狀況下 (ex. 32-bit JVM), 01/13 20:21
RockLee:Object 的 hashCode() 實作是否一定會傳回 unique 的值? 01/13 20:22
RockLee:有人發現過您用的 JVM 不是傳回 unique 的值嗎? 01/13 20:23
adrianshum:簡單一句:不該當hashCode會回傳unique值。這非其本意 01/13 22:40
RockLee:我了解 hashCode() 的意義, 但這並不是我的問題… 01/13 23:14
RockLee:因為 Object 的說明中提到: 01/13 23:17
RockLee:However, the programmer should be aware that 01/13 23:19
RockLee:producing distinct integer results for unequal objects 01/13 23:21
RockLee:may improve the performance of hashtables. 01/13 23:23
RockLee:所以我才想確認 Object 原始提供的 hashCode() 實作為何? 01/13 23:24
RockLee:lang/Object.html 01/13 23:26
qrtt1:那就去翻 source code 啊,翻手冊做什麼@@ 01/14 00:19
pzyc79:source code只會給你public native int hashCode();這行字 01/14 00:37
pzyc79:我想知道這種原生函式的原始碼去哪裡可以找到@@a; 01/14 00:42
RockLee:可是我的問題是, As much as is reasonably practical ... 01/14 00:45
RockLee:這段話是否要求所有 JVM 的實作, 在可行的狀況下, 01/14 00:47
RockLee:Object 的 hashCode() 傳回 unique 的值? 01/14 00:48
RockLee:似乎不是翻某個 JVM 的 source code 可以解決的... 01/14 00:49
pzyc79:就算hashcode真的是unique你也不能把當unique用… 01/14 01:10
PsMonkey:太難的事情我不懂,我只想問:你怎麼知道沒有被 override 01/14 16:13
tkcn:原 po 應該是單純指 "Object" 這個類別的實體 01/14 16:21
ClareQ:不可能是unique,且Object預設hash實作與記憶體位置有關 01/14 16:49
RockLee:我問的的確只是"Object"這個類別的hashCode() 01/14 20:27
RockLee:為什麼不可能是unique呢? 01/14 20:29
RockLee:如果回傳記憶體位置至少32-bit JVM就可以達到unique了不是 01/14 20:31
PsMonkey:要是我,我也不會跟你保證是 unique... 01/15 13:21