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());
}
}
You can convert HashMap keys into ArrayList or you can convert HashMap values into ArrayList or you can convert key-value pairs into ArrayList.
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.
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With