The map replaced all the same key values ββof the list object
I tried to replace the map data of only the selected index from the bean list, but it replaced all values ββfor every list object that contains the same key. If I create a new map object before putting the new value, then it works fine, but I wanted to know the reason why the following code is wrong.
public static void main(String[] args) {
List<PolicyAddlnInsuredBean> lst = new ArrayList<PolicyAddlnInsuredBean>();
PolicyAddlnInsuredBean pb = new PolicyAddlnInsuredBean();
Map<String, Map<String, Object>> epInfoMap = new HashMap<String, Map<String,Object>>();
Map<String,Object> map = new HashMap<String, Object>();
map.put("addtlnInsReqd", "YES");
map.put("selectedFlg", "No");
epInfoMap.put("AL", map);
pb.setEpInfoMap(epInfoMap);
lst.add(pb);
epInfoMap = new HashMap<String, Map<String,Object>>();
map = new HashMap<String, Object>();
map.put("addtlnInsReqd", "YES");
map.put("selectedFlg", "No");
epInfoMap.put("AL", map);
pb.setEpInfoMap(epInfoMap);
lst.add(pb);
lst.get(0).getEpInfoMap().get("AL").put("selectedFlg", "Yes");
System.out.println(lst);
}
My Pojo class:
public class PolicyAddlnInsuredBean{
private Map<String,Map<String,Object>> epInfoMap =new HashMap<String, Map<String,Object>>();
public Map<String, Map<String, Object>> getEpInfoMap() {
return epInfoMap;
}
public void setEpInfoMap(Map<String, Map<String, Object>> epInfoMap) {
this.epInfoMap = epInfoMap;
}
@Override
public String toString() {
return "PolicyAddlnInsuredBean [epInfoMap=" + epInfoMap + "]";
}
}
+3
source to share