使用HashMap的HashSet显示错误的值

时间:2016-09-18 06:00:21

标签: java hashmap unique hashset

当我尝试在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}]

1 个答案:

答案 0 :(得分:0)

您的x变量指向一(1)hm个实例,该实例随后被添加到HashMap两次(甚至三次,与您的HashSet块一起添加。 // add again实例将包含最后放置的值,该集将包含对同一映射的两个(或三个)引用。

创建两个单独的HashMap实例以使其正常工作:

HashMap