简体   繁体   English

如何防止 LinkedHashMap 替换键/值?

[英]How to prevent LinkedHashMap from replacing Key/Value?

Let's say that I have a LinkedHashMap<Integer,Point2D.Double> , and I put a key and a value to it, like .put(2,new Point2D.Double(34,32));假设我有一个LinkedHashMap<Integer,Point2D.Double> ,我给它放了一个键和一个值,比如.put(2,new Point2D.Double(34,32));

My problem is that sometimes I need to put a key and a value in it that already exists, and the LinkedHashMap replaces it.我的问题是有时我需要在其中放置一个已经存在的键和值,然后LinkedHashMap替换它。

Like, I already have the key 2 and the value Point2D.Double(34,32) , and I need to add it another time.就像,我已经有了键2和值Point2D.Double(34,32) ,我需要再次添加它。

Why is it replacing that key/value by adding the same to the map, and is there a way to solve this issue (maybe via another sort of map)?为什么它通过将相同的键/值添加到地图来替换该键/值,有没有办法解决这个问题(也许通过另一种地图)?

If the order of Point is not important, init your hashmap as:如果 Point 的顺序不重要,请将您的哈希图初始化为:

HashMap<Integer,HashSet<Point2D.Double>> hashmap = new HashMap<Integer,HashSet<Point2D.Double>>();

instead of using而不是使用

hashmap.put(1,new Point2D.Double(34,32));

use the following code:使用以下代码:

if(hashmap.get(key) == null){
  value = new HashSet<Point2D.Double>();
}else{
  value = hashmap.get(key);
}
value.add(point_to_add);
hashmap.put(key,value);

If the order of the inserted Points is important, use an (Array-)List instead of a hashSet如果插入点的顺序很重要,请使用 (Array-)List 而不是 hashSet

EDIT编辑

AS GPI mentioned: Using JAVA 8 you could also do it this way:正如 GPI 提到的:使用 JAVA 8 你也可以这样做:

map.computeIfAbsent(key, k -> new HashSet<>()).add(value)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM