简体   繁体   English

hashmap 中具有不同键的相同值

[英]Same values with different keys in a hashmap

Initially I put two entries with the same value into a hashmap.最初,我将两个具有相同值的条目放入 hashmap。 The value of the two entries is itself a map.这两个条目的值本身就是 map。 These entries have different keys.这些条目有不同的键。

Now I want to put new values into the map (the value) of the first entry.现在我想将新值放入第一个条目的 map(值)中。 The problem is that the map of the second entry (its value) is also changed as long as I change the first one.问题是只要我改变第一个条目,第二个条目的map(它的值)也改变了。 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.基本上,问题在于您没有将两个地图放入 map,而是将两个引用放入同一个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.要在外部有两个独立版本的内部 map,您需要在第二次放入之前对其进行复制。

You should be able to make a copy of a HashMap using its clone method.您应该能够使用其clone方法制作HashMap的副本。 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.

Good catch on putting the same reference under different keys.将相同的参考放在不同的键下很好。 However for solving I wouldn't use clone method and rather would use explicit copying: package com.au.psiu;但是为了解决问题,我不会使用clone方法,而是使用显式复制:

import java.util.HashMap;
import java.util.Map;

public class NoIdea {

    public static void main(String... args) {
        Map source = new HashMap();

        //Insert value into source
        Map copy1 = new HashMap();
        copy1.putAll(source);
        Map copy2 = new HashMap();
        copy2.putAll(source);

        Map mapOfMaps = new HashMap();
        mapOfMaps.put("key1", copy1);
        mapOfMaps.put("key2", copy2);
        //...and you can update maps separately
    }
}

Also you might want to take a look into google guava project - they have a lot useful APIs for collections.此外,您可能想看看 google guava 项目 - 他们为 collections 提供了很多有用的 API。

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

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