问题描述
我正在使用 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 混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!