問題描述
我正在使用 HashMap
,但我無法直接回答 get()
方法在發生沖突時如何工作.
I'm using a HashMap
and I haven't been able to get a straight answer on how the get()
method works in the case of collisions.
假設 n >1
個對象被放置在同一個 key 中.它們是否存儲在 LinkedList
中?它們是否被覆蓋,以便僅放置在該鍵中的最后一個對象不再存在?他們是否使用了其他碰撞方法?
Let's say n > 1
objects get placed in the same key. Are they stored in a LinkedList
? Are they overwritten so that only the last object placed in that key exists there anymore? Are they using some other collision method?
如果將它們放在 LinkedList
中,有沒有辦法檢索整個列表?如果沒有,是否有其他的 Java 內置地圖可供我執行此操作?
If they are placed in a LinkedList
, is there a way to retrieve that entire list? If not, is there some other built in map for Java in which I can do this?
就我的目的而言,單獨的鏈接將是理想的,就好像存在沖突一樣,我需要能夠查看列表并獲取有關其中所有對象的信息.在 Java 中執行此操作的最佳方法是什么?
For my purposes, separate chaining would be ideal, as if there are collisions, I need to be able to look through the list and get information about all the objects in it. What would be the best way to do this in Java?
感謝您的幫助!
推薦答案
它們是否被覆蓋,從而只有放置在該鍵中的最后一個對象不再存在?
Are they overwritten so that only the last object placed in that key exists there anymore?
是的,假設您使用相同的鍵放置多個值(根據 Object.equals
,而不是 Object.hashCode
.)這是在 Map.put
javadoc:
Yes, assuming you're putting multiple values with the same key (according to Object.equals
, not Object.hashCode
.) That's specified in the Map.put
javadoc:
如果映射先前包含鍵的映射,則舊值將替換為指定值.
If the map previously contained a mapping for the key, the old value is replaced by the specified value.
如果您想將一個鍵映射到多個值,最好使用 Guava 的 ListMultimap
, ArrayListMultimap
具體而言,它將鍵映射到值列表.(披露:我為 Guava 做出了貢獻.)如果你不能容忍第三方庫,那么你真的必須有一個 Map<Key, List<Value>>
,盡管這可以得到有點笨拙.
If you want to map a key to multiple values, you're probably better off using something like Guava's ListMultimap
, ArrayListMultimap
in specific, which maps keys to lists of values. (Disclosure: I contribute to Guava.) If you can't tolerate a third-party library, then really you have to have a Map<Key, List<Value>>
, though that can get a bit unwieldy.
這篇關于Java - 關于沖突處理和 get() 方法的 HashMap 混淆的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!