我试图将HashMap
存储在另一个HashMap
中,但第一次插入的值作为第二次插入值而更改。在HashMap中存储HashMap
这是我的代码。
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}]*/
我第一次插入第二“键,值”之后[2={4=2, 5=2, 6=2}, 1={4=2, 5=2, 6=2}]
得到输出作为1={1=1, 2=1, 3=1}]
我键“1”的值变更为“2”键。
明确影响您存储的对象。放不做副本,它直接引用该对象。你需要创建一个新的实例。 – njzk2