4

我试图存储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}] 在插入第二个“键,值”后第一次得到输出时,[2={4=2, 5=2, 6=2}, 1={4=2, 5=2, 6=2}]我将键“1”值更改为键“2”。

4

5 回答 5

5

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

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

Map#clear()不会你一个 Map的实例。因此,两个map11最终2都重用了相同的实例,map2因此您会看到所有值都在重复。

添加新值后尝试一次又一次地打印您的Map容器Map#clear()

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}]
于 2013-10-24T14:00:56.607 回答
0

HashMap map2您存储对in的引用map1,而不是副本。这就是为什么所有后续更改map2也会影响插入到map1.

于 2013-10-24T14:01:39.123 回答
0

你不应该清除地图。请注意,您添加map2的是使用此创建的 HashMap:

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

这意味着有使用地址内存值创建的对象。而这个地址内存值被放入“更大”的HashMap中。

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

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

map2.clear();

你必须这样做:

map2=new HashMap<>();
于 2013-10-24T14:02:00.987 回答
0

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

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

于 2013-10-24T14:02:37.717 回答
0

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

map1.clear();
map2.clear();
于 2014-10-01T09:12:07.250 回答