简体   繁体   中英

Map replaced all the same key value of list object

I was trying to replace map details of only selected index from list of bean but it replaced all the value for each list objects which contains the same key. If I am creating new object of map before going to put new value then it's working fine, but I wanted to know the reason why following code misbehave.

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 + "]";
  }

}

只有一个pb对象,两次添加到lst (原理:“检查new s”)。

相同的pb对象被添加到列表中两次。因此即使在第0个索引处更改pb对象时,更改也将反映在第一个索引处的对象上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM