6

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<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());
    }
}

2 Answers 2

19

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.

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

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());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see. I get it now. Thank you for the explanation. I will mark as correct in ten min. Thanks again.
0

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);

1 Comment

use 4 spaces at the beginning of any line of code to format your code better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.