Java 如何将 HashMap 添加到 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25293128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:03:29  来源:igfitidea点击:

How to add HashMap to ArrayList

javaandroidarraylist

提问by AhabLives

Can someone please tell me why the code below overwrites every element in the ArrayList with the most recent entry into the ArrayList? Or how to correctly add new elements of hashmaps to my ArrayList?

有人能告诉我为什么下面的代码会用最近进入 ArrayList 的条目覆盖 ArrayList 中的每个元素吗?或者如何将哈希图的新元素正确添加到我的 ArrayList 中?

ArrayList<HashMap<String, String>> prodArrayList = new ArrayList<HashMap<String, String>>();

HashMap<String, String> prodHashMap = new HashMap<String, String>();

public void addProd(View ap)
{
    // test arraylist of hashmaps
    prodHashMap.put("prod", tvProd.getText().toString());

    prodArrayList.add(prodHashMap);

    tvProd.setText("");

    // check data ///

    Log.e("myLog","Data prodArrayList in ADD Method Size = "+prodArrayList.size());

    for(int i=0; i< prodArrayList.size();i++)
    {
         Log.e("myLog","Data prodArrayList in ADD Method = "+prodArrayList.get(i).toString());
    }
}

采纳答案by Rod_Algonquin

problem:

问题:

prodHashMap.put("prod", tvProd.getText().toString());

You are using the same key each time you are adding an element to the the arraylist with the same reference to the HashMapthus changing its values.

每次将元素添加到 arraylist 时,您都使用相同的键,并HashMap对其值具有相同的引用。

Solution:

解决方案:

create a new instance of HashMapeach time you want to add it to the ArrayListto avoid changing its values upon calling addProd

HashMap每次要将其添加到 时创建一个新实例,ArrayList以避免在调用时更改其值addProd

public void addProd(View ap)
{
    // test arraylist of hashmaps
    HashMap<String, String> prodHashMap = new HashMap<String, String>();
    prodHashMap.put("prod", tvProd.getText().toString());

    prodArrayList.add(prodHashMap);

    tvProd.setText("");

    // check data ///

    Log.e("myLog","Data prodArrayList in ADD Method Size = "+prodArrayList.size());

    for(int i=0; i< prodArrayList.size();i++)
    {
         Log.e("myLog","Data prodArrayList in ADD Method = "+prodArrayList.get(i).toString());
    }
}

回答by umamaheshwar g

This is for adding multiple maps to List

这是用于将多个地图添加到列表

Map<String,Object> map1=new HashMap<>();
map1.  // add required items

Map<String,Object> map2=new HashMap<>();
map2.  // add required items

Map<String,Object> map3=new HashMap<>();
map3.  // add required items

List<String,Object> list=new ArrayList<>();

list.add(map1);

list.add(map2);

list.add(map3);