java - Why does clear hashmap method clears added map in array list -


i'm trying reuse same hashmap in example bellow populate list. first put values in map, add map list , clear map in order put again new values , add second set of values in list , on...

but, seems clear() method delete values added in list , if don't use clear() method every set of values added in list overwritten new set of values in end in particular example have 4 identical value sets in 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(); 

datalist.add(map) put reference map in list, it's not copy. when map.clear() afterwards, erases content of map in list too, because same object. datalist.add(map.clone()) instead or (preferably) 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: code looks use object instead of 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;   }    // getters , setters , other usefull code  } 

this should make code nicer , 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 ignore ;-)


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -