Java: create a list of HashMaps

前端 未结 6 554
甜味超标
甜味超标 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条回答
  • 2021-01-02 02:43

    Yes, hash map from this piece of code

    list.add(new HashMap());
    

    is never referenced. So eventually you get a list of 3 items, 2 of which are identical however.

    0 讨论(0)
  • 2021-01-02 02:43

    have three adds to the list. the first add is to a new map instance; you never set any values. The second add you pass in a reference to nMap, which has 1, yes. The third add you pass the same reference. So the Map now has 3 references, the first to a map you never added any values to, the next 2 to the same map. which is why you get the same output.

    0 讨论(0)
  • 2021-01-02 02:47

    Something which is maybe also worth mention it, is that you should define the type of the elements you use in the List, for the HashMap its not possible because you are mixing Integers and Strings.

    And another thing is that you should use the List interface as type, so you are able to change the implementation (ArrayList or whatever) in the future.

    Here the corrected code:

    Map mMap = new HashMap();
    List<Map> list = new ArrayList();
    
    0 讨论(0)
  • 2021-01-02 03:04

    You are never saving a reference to this Map:

    list.add(new HashMap());
    
    0 讨论(0)
  • 2021-01-02 03:08

    When you put the same key name in the map then values will be overridden to same key. suppose we have

    mMap.put("start",1);
    mMap.put("start",2);
    mMap.put("start",3);
    mMap.put("start",4);
    

    it will not make map of length 4, as the key("start") is same so it will override the values on the same key. so you will get the get only one value (4) against "start" key. To avoid this you will have to change the name of keys in a hashmap but in your scenaro, you need an other instance of hashmap to save the key and values as you are maintaining the arralist.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题