Java - HashMap confusion about collision handling and the get() method(Java - 关于冲突处理和 get() 方法的 HashMap 混淆)
问题描述
我正在使用 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 混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java - 关于冲突处理和 get() 方法的 HashMap 混淆


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01