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

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

问题描述

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



例如:

  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

如果确实是链式的


键值14th Value---> 3rd Value--->2nd Value---->
1st Value


我得到其他值?



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



如果是线性链接,我的第二个问题是



。如何删除键的任何一个值。假设我想从我的hashmap中删除第四个值,并希望保留所有其他值为同一个键,我该怎么办?



如果我做


hmap.remove(1);


它会删除完整的链。

解决方案

HashMap 相同的键。



链接用于解决哈希冲突,即当不同的密钥具有相同的哈希时的情况。因此,它不是使用相同的键存储多个值,而是关于其键具有相同散列的多个值。



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



如果你需要一个multimap,你可以维护一个 Map of List s(由matsev建议),或者使用第三方库中现有的多重映射实现,例如 Google Guava



另请参阅:




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.

For example :

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");

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

if Indeed it does chaining like

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

How can I get the other values?

hmap.get(1) only returns the 1st value.

My second question is,

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?

if I do

hmap.remove(1);

, it removes the complete chain.

解决方案

HashMap cannot store multiple values for the same key.

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.

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.

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.

See also:

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

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