简体   繁体   English

无论如何在Java HashMap中有两个相同的键,但是值不同?

[英]Anyway to have two of the same keys, but different values in Java HashMap?

I'm using a HashMap to contain a misspelled word, and a int array that contains its offset in the document, the line number it is on, and the length of that misspelled word. 我正在使用HashMap来包含一个拼写错误的单词,以及一个int数组,该数组包含其在文档中的偏移量,它所在的行号以及该拼写错误的单词的长度。 By default, HashMap replaces the old values if the key is already contained. 默认情况下,如果密钥已包含,则HashMap替换旧值。 I would like to keep those values, and have duplicate keys. 我想保留这些值,并具有重复的键。

Is there anyway to accomplish this? 反正有做到这一点吗?

You CANNOT have duplicate keys in Map but you can create a MultiMap ie A map to associate a single key with multiple values. 您在Map不能有重复的键,但是您可以创建一个MultiMap,即将单个键与多个值关联的Map。 Something like this: 像这样:

Map<String,ArrayList<String>> myMap = new HashMap<String,ArrayList<String>>();

or you can use readymade multi-map implementations such as: 或者您可以使用现成的多地图实现,例如:

No, a HashMap is always uniquely keyed. 不,HashMap始终是唯一键。 If you need aap that a key can have multiple values, look at Guava's MultiMap 如果需要一个键可以具有多个值的信息,请查看番石榴的MultiMap

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 hashmap 中具有不同键的相同值 - Same values with different keys in a hashmap 我有两个 hashmap HashMap <string,list<string> &gt; 在这种格式下,如何比较两个值是否相同或不同的键</string,list<string> - I have two hashmap HashMap<String,List<String>> in this format how to compare both the values are same or not with same keys 如何将具有相同键的两个 HashMap 中的值(不同数据类型)放入新的第三个 HashMap? - How do I put in the values (of different data types) from two HashMaps with the same keys into a new third HashMap? Java:带有两个键的HashMap - Java: HashMap with two keys 为什么java.util.HashMap中的支持表索引对于两个不同的提供键是相同的? - Why can index of backing table in java.util.HashMap be the same for two different provided keys? 具有不同hashCode的两个密钥可以在Java中的HashMap中成为同一个存储桶的一部分吗? - Can two keys having different hashCode be a part of same bucket in HashMap in Java? 当不同的键具有相同的哈希码时,为什么在 HashMap 中没有冲突 - Why is there no collision in a HashMap when different keys have the same hash code 为什么 HashMap 不能有不同的 NaN 值作为键? - Why can't HashMap have different NaN values as keys? 如果HashMap中的两个键相同,如何打印错误消息? (JAVA) - How to print an error message if two keys are the same in a HashMap? (JAVA) Java HashMap 使用流从两个不同的 Set 源添加键? - Java HashMap adding keys from two different Set sources with stream?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM