在散列图中具有不同键的相同值 [英] Same values with different keys in a hashmap
问题描述
现在我想将新值放入第一个条目的映射(值)中。问题是,只要我改变第一个条目(它的值)的地图也会改变。这两个不同的键以某种方式引用相同的值(地图)。
为了编辑最初相同的值的值,我应该怎么做?基本上,问题在于你没有将两个地图放入地图中,而是将两个地图放入地图中,而是将两个地图对相同地图的引用。
要在外部地图中拥有两个独立版本的内部地图,您需要在第二次放入内部地图之前制作其副本。
您应该可以使用它的 clone
来复制 HashMap
方法。请注意,虽然这确实为您提供了两张不同的地图,但两张地图中的实际值是相同的。这意味着,如果复制的地图的内容是可变的,并且您更改了它们,它们仍然会在两处发生更改。
澄清:
HashMap< Object,Object> map1 = new HashMap< Object,Object>()//这是您的原始地图。
map1.put(key,mutableObject)
HashMap< Object,Object> map2 = map1.clone();
map2.put(something,something else); // map1不变
map2.get(key)。change(); //可变对象在两个map 。
Initially I put two entries with the same value into a hashmap. The value of the two entries is itself a map. These entries have different keys.
Now I want to put new values into the map (the value) of the first entry. The problem is that the map of the second entry (its value) is also changed as long as I change the first one. The two different keys somehow reference the same value (map).
What should I do in order to edit the values of the initially identical values separately from each other?
Basically, the issue is that you did not put two maps into your map, but rather put two references to the same map.
To have two independent versions of the inner map in the outer one, you need to make a copy of it before putting it in a second time.
You should be able to make a copy of a HashMap
using its clone
method. Note that while this does get you two different maps, the actual values in the two maps are the same. This means that if the copied map's contents are mutable and you change them, they will still change in both places.
To clarify:
HashMap<Object, Object> map1 = new HashMap<Object, Object>()// This is your original map.
map1.put("key", mutableObject)
HashMap<Object, Object> map2 = map1.clone();
map2.put("something", "something else");// map1 is unchanged
map2.get("key").change();// the mutable object is changed in both maps.
这篇关于在散列图中具有不同键的相同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!