Search code examples
javahashmapuniquehashset

HashSet with HashMap is showing wrong values


When I am trying to add HashMap in HashSet it is showing wrong values.

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);

OUTPUT:

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}]

EXPECTED OUTPUT:

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}]

Solution

  • Your hm variable points to one (1) HashMap instance that is subsequently added to the HashSet twice (or even three times, with your // add again block). The HashMap instance will contain the values that have been put last, and the set will contain two (or three) references to the same map.

    Create two separate HashMap instances to make it work correctly:

    HashSet<HashMap> hs = new HashSet<HashMap>();
    HashMap<String, String> hm1 = new HashMap<String, String>();
    hm1.put("name", "Amit");
    hm1.put("device_id", "192.168.1.100");
    hm1.put("ip", "192.168.1.100");
    
    hs.add(hm1);
    
    HashMap<String, String> hm2 = new HashMap<String, String>();
    hm2.put("name", "Mani");
    hm2.put("device_id", "192.168.1.102");
    hm2.put("ip", "192.168.1.102");
    
    hs.add(hm2);