如何将HashMap添加到ArrayList

时间:2021-12-23 23:13:47

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中的每个元素?或者如何正确地将新的hashmaps元素添加到我的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());
    }
}

1 个解决方案

#1


17  

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 HashMap thus changing its values.

每次使用与HashMap相同的引用向元组添加元素时使用相同的键,从而更改其值。

Solution:

解:

create a new instance of HashMap each time you want to add it to the ArrayList to avoid changing its values upon calling addProd

每次要将其添加到ArrayList时创建HashMap的新实例,以避免在调用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());
    }
}

#1


17  

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 HashMap thus changing its values.

每次使用与HashMap相同的引用向元组添加元素时使用相同的键,从而更改其值。

Solution:

解:

create a new instance of HashMap each time you want to add it to the ArrayList to avoid changing its values upon calling addProd

每次要将其添加到ArrayList时创建HashMap的新实例,以避免在调用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());
    }
}