gpt4 book ai didi

java - 在 HashMap 内部存储 HashMap

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:16:29 26 4
gpt4 key购买 nike

我试图将 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}]插入第二个“key, value” [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}]

关于java - 在 HashMap 内部存储 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com