假设我有一个 LinkedHashMap<Integer,Point2D.Double>
,然后我为其添加一个键和一个值,例如 .put(2,new Point2D.Double(34,32));
我的问题是,有时我需要在其中放入已经存在的键和值,而 LinkedHashMap
替换它。
就像,我已经有了 key 2
和值 Point2D.Double(34,32)
,我需要再次添加。
为什么要通过将相同的键/值添加到 map 来替换该键/值,有没有办法解决这个问题(也许通过另一种 map )?
最佳答案
如果 Point 的顺序不重要,请将 HashMap 初始化为:
HashMap<Integer,HashSet<Point2D.Double>> hashmap = new HashMap<Integer,HashSet<Point2D.Double>>();
而不是使用
hashmap.put(1,new Point2D.Double(34,32));
使用以下代码:
if(hashmap.get(key) == null){
value = new HashSet<Point2D.Double>();
}else{
value = hashmap.get(key);
}
value.add(point_to_add);
hashmap.put(key,value);
如果插入点的顺序很重要,请使用(Array-)List而不是hashSet
编辑
正如 GPI 提到的:使用 JAVA 8 你也可以这样做:
map.computeIfAbsent(key, k -> new HashSet<>()).add(value)
关于java - 如何防止LinkedHashMap替换Key/Value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42133777/