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


2 answers


There is only one object pb

added twice to lst

(principle: "check new

s").



+5


source


The same pb object is added twice to the list. Therefore, even when you change the pb object to the 0th index, the change will be reflected on the object with the 1st index.



0


source







All Articles