Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map replaced all the same key value of list object

Tags:

java

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

}
like image 383
michaeln peterson Avatar asked Nov 29 '25 23:11

michaeln peterson


1 Answers

There is only one pb object, added twice to lst (principle: "check the news").

like image 199
Joop Eggen Avatar answered Dec 01 '25 11:12

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!