Java – why does the clear HashMap method clear the map added in the array list

I'm trying to reuse the same HashMap, such as the following example to populate the list First, I add some values to the map, add the map to the list, then clear the map to add new values again, add a second set of values to the list, and so on

However, it seems that the clear () method also deletes the values previously added in the list. If I don't use the clear () method, each group of values previously added in the list will be overwritten by the new value set, so that finally in this special example, I will have four identical value sets in the list

What did I do 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,secondOption);
    dataList.add(map);
    map.clear();

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

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

Solution

dataList. Add (map) will place a reference to the map in the list, so it is not a copy Then when you execute map After clear (), it will also delete the contents of the map in the list because it is the same object Change to datalist Add (map. Clone()) or (preferably) make map = new HashMap < > (); then.

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 can use objects instead of maps:

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 better and more readable

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

But ignore it at will; -)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>