java HashMap 如何进行链接?如何访问所有碰撞值? [英] How java HashMap does chaining? how to access all collision values?

查看:15
本文介绍了java HashMap 如何进行链接?如何访问所有碰撞值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读到 HashMap 使用链接来解决冲突.但如果是这样的话.如何访问具有相同键值的所有元素.

I have read somewhere that HashMap uses chaining to resolve collisions. But if that is the case. how can i access all the elements with same key value.

例如:

HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(1, "1st value");
hmap.put(1, "2nd value");
hmap.put(1, "3rd value");
hmap.put(1, "4th value");

现在,如果我执行 hmap.get(1) 它返回第四个值"

Now, if I do hmap.get(1) it returns "4th Value"

如果确实像这样链接

关键值 1 第 4 个值" ---> 第 3 个值" --->第 2 个值"---->第一价值"

Key values 1 "4th Value" ---> "3rd Value"--->"2nd Value"----> "1st Value"

如何获取其他值?

hmap.get(1) 只返回第一个值.

我的第二个问题是,

如果它进行线性链接.如何删除键的任何一个值.假设我想从我的哈希图中删除第 4 个值",并想保留同一个键的所有其他值,我该怎么做?

if it does linear chaining. How can I remove any one value for a key. suppose I want to remove "4th value" from my hashmap and want to keep all other values for same key, how can i do it?

如果我这样做

hmap.remove(1);

hmap.remove(1);

,它删除了完整的链.

推荐答案

HashMap 不能为同一个键存储多个值.

HashMap cannot store multiple values for the same key.

Chaining 用于解决哈希冲突,即不同键具有相同的情况哈希.因此,这不是关于使用相同的键存储多个值,而是关于键具有相同哈希值的多个值.

Chaining is used to resolve hash collisions, i.e. situations when different keys have the same hash. So, it's not about storing multiple values with the same key, it's about multiple values whose keys have the same hashes.

可以为同一个键存储多个值的数据结构称为多重映射.不幸的是,JRE 中没有内置的 multimap 实现.

Data structure that can store multiple values for the same key is called a multimap. Unfortunately, there is no built-in implementation of multimap in JRE.

如果您需要多图,您可以维护 ListMap(如 matsev 建议),或使用第三方库中现有的多图实现,例如 Google Guava.

If you need a multimap, you can maintain a Map of Lists (as suggested by matsev), or use an existing multimap implementation from a third-party library, such as Google Guava.

另见:

这篇关于java HashMap 如何进行链接?如何访问所有碰撞值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆