1

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?

no_idea
  • 11
  • 1
  • 2

2 Answers2

5

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.
Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
1

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.

Petro Semeniuk
  • 6,970
  • 10
  • 42
  • 65