Reputation: 226
I have tried to store HashMap
inside another HashMap
but first inserted values changed as second time inserted value.
Here is my code.
HashMap<String ,HashMap<Integer ,Integer>> map1=new HashMap<>();
HashMap<Integer ,Integer> map2=new HashMap<>();
map2.put(1,1);
map2.put(2,1);
map2.put(3,1);
map1.put("1", map2);
System.out.println("After Inserting first value "+map1.entrySet());
/* OutPut: After Inserting first value [1={1=1, 2=1, 3=1}]*/
map2.clear(); //i cleared map 2 values
map2.put(4,2);
map2.put(5,2);
map2.put(6,2);
map1.put("2", map2);
System.out.println("After Inserting second value "+map1.entrySet());
/*output : After Inserting second value [2={4=2, 5=2, 6=2}, 1={4=2, 5=2, 6=2}]*/
The first time I got output as 1={1=1, 2=1, 3=1}]
after inserting second "key, value" [2={4=2, 5=2, 6=2}, 1={4=2, 5=2, 6=2}]
I got key "1" values changed to key "2".
Upvotes: 4
Views: 8845
Reputation: 51721
You need to create a new instance of HashMap
before the second put()
call
// map2.clear();
map2 = new HashMap<Integer, Integer>();
Map#clear()
does not give you a new Map
instance. Hence, both map1
keys 1
and 2
end up reusing the same instance of map2
and hence you see all the values repeat themselves.
Try printing your Map
container after Map#clear()
and again after adding new values
map2.clear(); //i cleared map 2 values
System.out.println("After clearing "+map1.entrySet());
map2.put(4,2);
map2.put(5,2);
map2.put(6,2);
System.out.println("After adding new values "+map1.entrySet());
You can clearly see it affecting key 1
as well.
Output :
After Inserting first value [1={1=1, 2=1, 3=1}]
After clearing [1={}]
After adding new values [1={4=2, 5=2, 6=2}]
After Inserting second value [2={4=2, 5=2, 6=2}, 1={4=2, 5=2, 6=2}]
Upvotes: 5
Reputation: 4551
Your first inserted values are changed because first reference is referring to map2 and so does second reference. map2 object is same and it is referred in both places.
I guess what you want is create new object for each map2
Upvotes: 0
Reputation: 23049
You SHOULD NOT clear the map. Note that you adding HashMap map2
which is created with this :
HashMap<Integer ,Integer> map2=new HashMap<>();
It means there is object created with adress memory value. And this address memory value is put into the "bigger" HashMap.
If you clear/change map2
, you also clear it in your bigger HashMap, because it is just pointing to the same object!
You have to create new instance, so instead of
map2.clear();
You have to do this:
map2=new HashMap<>();
Upvotes: 0
Reputation: 71009
You store a reference to the HashMap
map2
in map1
, not a copy. That is why all subsequent changes to map2
also affect the first map inserted into map1
.
Upvotes: 0