I'm working with HashMap since few days, and facing below weird situation.
Case 1:Changed Key which is already existing in HashMap, and print HashMap Case 2: Changed key which is already existing in HashMap and Put that key again into the HashMap. Print HashMap.
Please find below code as well as two different output of two case.
Could you please anyone let me know, whats going on in below code.
import java.util.HashMap; import java.util.Set; class Emp{ private String id ; public String getId() { return id; } public void setId(String id) { this.id = id; } public Emp(String id) { super(); this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Emp other = (Emp) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "Emp [id=" + id + "]"; } } public class HashMapChanges { public static void main(String[] args) { // TODO Auto-generated method stub Emp e1 = new Emp("1"); Emp e2 = new Emp("2"); Emp e3 = new Emp("3"); Emp e4 = new Emp("4"); HashMap<Emp, String> hm = new HashMap<Emp,String>(); hm.put(e1,"One"); hm.put(e2,"Two"); hm.put(e3,"Three"); hm.put(e4,"Four"); e1.setId("5"); /** Uncomment below line to get different output**/ //hm.put(e1,"Five-5"); Set<Emp> setEmpValue = hm.keySet(); for(Emp e : setEmpValue){ System.out.println("Key"+ e +" Value "+ hm.get(e)); } } } Output of above code :
KeyEmp [id=2] Value Two KeyEmp [id=5] Value null KeyEmp [id=4] Value Four KeyEmp [id=3] Value Three Output After uncommenting line
KeyEmp [id=5] Value Five-5 KeyEmp [id=2] Value Two KeyEmp [id=5] Value Five-5 KeyEmp [id=4] Value Four KeyEmp [id=3] Value Three