Why does clear hashmap method clears added map in array list

Tags: ,



I’m trying to reuse same HashMap like in example bellow to populate list. First I put some values in the map, add map to the list and then clear map in order to put again new values and add second set of values in the list and so on…

But, it seems that clear() method also delete values previously added in the list and if I don’t use clear() method every set of values previously added in the list is overwritten with new set of values so that in the end in this particular example i will have 4 identical value sets in the list.

What I’m doing wrong?

    List<HashMap<String, String>>dataList = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> map = new HashMap<String, String>();

    map.put(Answer.ID, "0");
    map.put(Answer.IMAGE, "color_icon_awesome");
    map.put(Answer.TITLE, firstOption);
    dataList.add(map);
    map.clear();             

    map.put(Answer.ID, "1");
    map.put(Answer.IMAGE, "color_icon_awesome");
    map.put(Answer.TITLE, secondOption);
    dataList.add(map);
    map.clear();

    map.put(Answer.ID, "2");
    map.put(Answer.IMAGE, "color_icon_awesome");
    map.put(Answer.TITLE, thirdOption);
    dataList.add(map);
    map.clear();

    map.put(Answer.ID, "3");
    map.put(Answer.IMAGE, "color_icon_awesome");
    map.put(Answer.TITLE, fourthOption);
    dataList.add(map);
    map.clear();

Answer

dataList.add(map) will put a reference to map in the list, so it’s not a copy. When you then do map.clear() afterwards, it erases the content of the map in the list too, because it is the very same object. Do dataList.add(map.clone()) instead or (preferably) do map = new HashMap<>(); afterwards.

map.put(Answer.ID, "0");
map.put(Answer.IMAGE, "color_icon_awesome");
map.put(Answer.TITLE, firstOption);
dataList.add(map);
map = new HashMap<>();

Sidenote: Your code looks like you could use an object instead of the map:

class AnswerObject {

  private String id;
  private String image;
  private String title;

  public AnswerObject(String id, String image, String title) {
      this.id = id;
      this.image = image;
      this.title = title;
  }

  // some getters and setters and some other usefull code

}

This should make your code nicer and more readable

List<AnswerObject> dataList = new ArrayList<>();
dataList.add(new AnswerObject("0", "color_icon_awesome", firstOption));
dataList.add(new AnswerObject("1", "color_icon_awesome", secondOption));
dataList.add(new AnswerObject("2", "color_icon_awesome", thirdOption));
dataList.add(new AnswerObject("3", "color_icon_awesome", fourthOption));

But feel free to ignore that 😉



Source: stackoverflow