在散列图中具有不同键的相同值 [英] Same values with different keys in a hashmap

查看:122
本文介绍了在散列图中具有不同键的相同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初我将两个具有相同值的条目放入散列表中。这两个条目的价值本身就是一张地图。这些条目有不同的键。

现在我想将新值放入第一个条目的映射(值)中。问题是,只要我改变第一个条目(它的值)的地图也会改变。这两个不同的键以某种方式引用相同的值(地图)。



为了编辑最初相同的值的值,我应该怎么做?地图放入地图中,而是将两个地图放入地图中,而是将两个地图相同地图的引用。



要在外部地图中拥有两个独立版本的内部地图,您需要在第二次放入内部地图之前制作其副本。



您应该可以使用它的 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屋!

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