当我尝试在HashMap
中添加HashSet
时,它显示错误的值。
CODE :
HashSet<HashMap> arList = new HashSet<HashMap>();
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("name", "Amit");
hm.put("device_id", "192.168.1.100");
hm.put("ip", "192.168.1.100");
System.out.println("hm:"+hm);
arList.add(hm);
//add again
arList.add(hm);
hm.put("name", "Mani");
hm.put("device_id", "192.168.1.102");
hm.put("ip", "192.168.1.102");
arList.add(hm);
System.out.println("hm:"+hm);
System.out.println("arList: " + arList);
输出:
hm:{name=Amit, device_id=192.168.1.100, ip=192.168.1.100}
hm:{name=Mani, device_id=192.168.1.102, ip=192.168.1.102}
arList: [{name=Mani, device_id=192.168.1.102, ip=192.168.1.102}, {name=Mani, device_id=192.168.1.102, ip=192.168.1.102}]
预期输出:
hm:{name=Amit, device_id=192.168.1.100, ip=192.168.1.100}
hm:{name=Mani, device_id=192.168.1.102, ip=192.168.1.102}
arList: [{name=Amit, device_id=192.168.1.100, ip=192.168.1.100}, {name=Mani, device_id=192.168.1.102, ip=192.168.1.102}]
答案 0 :(得分:0)
您的x
变量指向一(1)hm
个实例,该实例随后被添加到HashMap
两次(甚至三次,与您的HashSet
块一起添加。 // add again
实例将包含最后放置的值,该集将包含对同一映射的两个(或三个)引用。
创建两个单独的HashMap
实例以使其正常工作:
HashMap