1

I am trying to add hashmaps to array list. But the map(completeEntrie) is overriding the previous values when I am trying to add more than one value to arraylist(listOfCompleteEntries)

public class MapExample {

    public static void main(String a[]) {
        ArrayList listOfCompleteEntries = new ArrayList();
        Map<String, String> completeEntrie = new HashMap<String, String>();

        for (int i = 0; i < 3; i++) {

            completeEntrie.put("KEY_NAME", "Number:" + i);
            System.out.print(completeEntrie.toString());
            listOfCompleteEntries.add(completeEntrie);
            System.out.println(listOfCompleteEntries.toString());
        }
        System.out.println(listOfCompleteEntries.toString());
    }
}

Output for the above code is

{KEY_NAME=Number:0}[{KEY_NAME=Number:0}]
{KEY_NAME=Number:1}[{KEY_NAME=Number:1}, {KEY_NAME=Number:1}]
{KEY_NAME=Number:2}[{KEY_NAME=Number:2}, {KEY_NAME=Number:2}, {KEY_NAME=Number:2}]
[{KEY_NAME=Number:2}, {KEY_NAME=Number:2}, {KEY_NAME=Number:2}]

But i want the output to be like this

{KEY_NAME=Number:0}[{KEY_NAME=Number:0}]
{KEY_NAME=Number:1}[{KEY_NAME=Number:0}, {KEY_NAME=Number:1}]
{KEY_NAME=Number:2}[{KEY_NAME=Number:0}, {KEY_NAME=Number:1}, {KEY_NAME=Number:2}]
[{KEY_NAME=Number:0}, {KEY_NAME=Number:1}, {KEY_NAME=Number:2}]

Also please explain why is this map overriding the previous map in arraylist. Thanks for your help.

2
  • What does the title have to do with the question? Commented Apr 4, 2013 at 20:16
  • What does the title of your question have to do with the question? Commented Apr 4, 2013 at 20:16

1 Answer 1

2

Despite the irrelevant title, you need to construct a new map instance for each unique entry you want to add to the array list. Without this, you are modifying the same map instance.

Sign up to request clarification or add additional context in comments.

Comments

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.