Same values with different keys in a hashmap

爱⌒轻易说出口 提交于 2019-12-11 06:37:44

问题


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?


回答1:


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.



回答2:


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;

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.



来源:https://stackoverflow.com/questions/6687157/same-values-with-different-keys-in-a-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!