Joe
Joe

Reputation: 1508

my ArrayList is overwriting previous data

I am trying simple ArrayList example to solve some problem with my other code but this simple code is giving wrong output.

I have create an Arraylist of Hashmap, put 3 key/value pairs in that Hashmap and then put that Hashmap in the ArrayList, like this,

public class SortData {

    public static void main (String [] args){

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

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


        myHashMap.put("title",  "first Title");
        myHashMap.put("date",   "This is date");
        myHashMap.put("number", "5");

        myArrayList.add(0, myHashMap);

but when I try to add more data in the array list,

import java.util.ArrayList;
import java.util.HashMap;

public class SortData {

    public static void main (String [] args){

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

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


        myHashMap.put("title",  "first Title");
        myHashMap.put("date",   "This is date");
        myHashMap.put("number", "5");

        myArrayList.add(0, myHashMap);


        myHashMap.put("title",  "Second Title");
        myHashMap.put("date",   "This is 2nd date");
        myHashMap.put("number", "2");

        myArrayList.add(1, myHashMap);

        myHashMap.put("title",  "Third Title");
        myHashMap.put("date",   "This is 3rd date");
        myHashMap.put("number", "7");

        myArrayList.add(2, myHashMap);


        System.out.println(myArrayList.get(0)+"");
        System.out.println(myArrayList.get(1)+"");
        System.out.println(myArrayList.get(2)+"");


    }


}

The output is,

{title=Third Title, number=7, date=This is 3rd date}
{title=Third Title, number=7, date=This is 3rd date}
{title=Third Title, number=7, date=This is 3rd date}

Why the previous values in ArrayList are overwritten ? I have tried both,

myArrayList.add(Hashmap()), and myArrayList.add(int index, Hashmap()) but the output is the same

Upvotes: 0

Views: 3388

Answers (1)

rgettman
rgettman

Reputation: 178323

The ArrayList adds a reference to the HashMap that you've added, not a copy. You're adding the same HashMap to the ArrayList 3 times. After each add, you change the contents with more put calls, which overwrite the pre-existing values, because of the same key.

myArrayList[ o , o , o ]
             |   |   |
             +---+   |
             |       |
             +-------+
             |
             v
             myHashMap

To add different contents, add different HashMaps each time, by running

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

after the first 2 adds.

myArrayList[ o , o , o ]
             |   |   +-> HashMap
             |   |   
             |   +-----> HashMap
             |
             +---------> HashMap

Upvotes: 6

Related Questions