gpt4 book ai didi

java - 我不明白我的输出。为什么我两次得到同样的东西?

转载 作者:行者123 更新时间:2023-11-30 07:14:27 24 4
gpt4 key购买 nike

下面的程序维护了 2 个数据结构,命名为:

map of type HashMap
map_1 also of type HashMap

在开头 map 填充了 key : 1value : suhail。然后将此映射插入到 map_1 中,键为 20

map 再次填充了 key : 1 和另一个 value : CSE。此 map 再次插入 map_1

import java.util.*;

class KeyTest {
public static void main(String args[]) {
Map<Integer,String> map = new HashMap<Integer,String>();

Map<Integer,Object> map_1 = new HashMap<Integer,Object>();

map.put(1,"suhail");

map_1.put(20,map);

map.put(1,"CSE");

map_1.put(21,map);

Set<Integer> keys = map_1.keySet();
Iterator i = keys.iterator();
while(i.hasNext()) {
System.out.println(map_1.get((Integer)i.next()));
}

}
}

这是我在打印 map_1 值时得到的:

{1=CSE}
{1=CSE}

但这不是我所期望的。根据我的说法,程序应该是这样运行的:

[1,suhail]--> map
[20,[1,suhail]]---> map_1
[1,CSE]--> map (A replace, because of the same keys)
[21,[1,CSE]]--->map_1

所以输出应该是:

[1,suhail]
[1,CSE]

谁能解释一下,为什么我得不到这个输出

最佳答案

当您将对象 map 插入 map_1 时,它不会被复制。当您在 map_1 之外修改它时,存储的对象也会被修改,因为它是同一个对象。

将新 map 重新分配给map 以解决此问题:

Map<Integer,Object> map_1 = new HashMap<Integer,Object>();
Map<Integer,String> map = new HashMap<Integer,String>();

map.put(1,"suhail");
// The first "map" object gets inserted
map_1.put(20,map);

// Make a new object
map = new HashMap<Integer,String>();

map.put(1,"CSE");
// Now the second object gets inserted
map_1.put(21,map);

关于java - 我不明白我的输出。为什么我两次得到同样的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18463731/

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