Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add HashMap to ArrayList

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());
    }
}
like image 949
AhabLives Avatar asked Aug 13 '14 18:08

AhabLives


People also ask

Can we add HashMap to ArrayList?

You can convert HashMap keys into ArrayList or you can convert HashMap values into ArrayList or you can convert key-value pairs into ArrayList.

Can we have List of HashMap?

HashMap and List in Java. Java provides us with different data structures with various properties and characteristics to store objects. Among those, HashMap is a collection of key-value pairs that maps a unique key to a value. Also, a List holds a sequence of objects of the same type.


1 Answers

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());
    }
}
like image 53
Rod_Algonquin Avatar answered Sep 30 '22 21:09

Rod_Algonquin