Java - 关于冲突处理和 get() 方法的 HashMap 混淆

Java - HashMap confusion about collision handling and the get() method(Java - 关于冲突处理和 get() 方法的 HashMap 混淆)
本文介绍了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 混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)