繁体   English   中英

在HashMap中存储HashMap

[英]Storing HashMap inside 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}]*/

插入第二个“键,值”后1={1=1, 2=1, 3=1}]我第一次输出为1={1=1, 2=1, 3=1}] [2={4=2, 5=2, 6=2}, 1={4=2, 5=2, 6=2}]我将键“1”值更改为键“2”。

您需要在第二次put()调用之前创建一个新的HashMap实例

// map2.clear();
map2 = new HashMap<Integer, Integer>();

Map#clear() 给你一个新的 Map实例。 因此, map112最终都会重用map2相同实例,因此您会看到所有值都重复出现。

尝试在Map#clear()之后打印Map容器,并在添加新值之后再次打印

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()); 

您也可以清楚地看到它对键1影响。

输出

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}]

您在map1存储对HashMap map2的引用,而不是副本。 这就是为什么map2所有后续更改也会影响插入到map1的第一个地图的原因。

你不应该清除地图。 请注意,您添加了使用以下创建的HashMap map2

HashMap<Integer ,Integer> map2=new HashMap<>(); 

这意味着存在使用地址内存值创建的对象。 并将此地址内存值放入“更大”的HashMap中。

如果你清除/更改map2 ,你也可以在更大的HashMap中清除它,因为它只是指向同一个对象!

你必须创建新的实例,所以而不是

map2.clear();

你必须这样做:

map2=new HashMap<>();

您的第一个插入值已更改,因为第一个引用是指map2,第二个引用也是如此。 map2对象是相同的,它在两个地方都被引用。

我想你想要的是为每个map2创建新对象

尝试清除两张地图。 有用。

map1.clear();
map2.clear();

暂无
暂无

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

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