Java: create a list of HashMaps

前端 未结 6 580
甜味超标
甜味超标 2021-01-02 02:36

I tried to create a list of maps. In the following code, I\'m expecting to get

[{start=1,text=ye}, {start=2,text=no}]

however, I only got

6条回答
  •  梦毁少年i
    2021-01-02 03:09

    You need to create a new HashMap for every entry, instead of reusing the existing one. This would work:

    HashMap mMap = new HashMap();
    mMap.put("start",1);
    mMap.put("text","yes");
    list.add(mMap); 
    mMap = new HashMap(); // create a new one!
    mMap.put("start",2);
    mMap.put("text","no");
    list.add(mMap); 
    

    also, you can remove the list.add(new HashMap()); as that adds an empty map to your list that is never populated.

提交回复
热议问题