-3

I was running a code where after I populate a hash in each iteration I add it to the arraylist so the values from all the iterations are stored in the arraylist. My code is below-

public class FirstRepeated {
        public static void main(String[] args) {
        // TODO Auto-generated method stub
         HashMap<String, Integer> map  = new HashMap<String, Integer>();
         List<HashMap<String, Integer>> list = new ArrayList<HashMap<String, Integer>>();
        for(int i=0;i<5;i++) {          
            map.put("test", i);
            list.add(map);
        }
        System.out.println(map);
        System.out.println(list);
    }
}

The output thats being printed is

{test=4}
[{test=4}, {test=4}, {test=4}, {test=4}, {test=4}]

But, AFAIK the output expected is

{test=4}
[{test=0}, {test=1}, {test=2}, {test=3}, {test=4}]

Can anyone please tell me whats the mistake ? I tried to debug it but before I execute the list.add(map); the value in list is being updated. Ex:-

Iteration 2 (i=1)

Value in list after iteration 1 (i=0) is 
[{test=0}]
But when the execution reaches  map.put("test", i);
The value in list is being updated to [{test=1}] 
and after the execution of the line list.add(map) 
value is being updated in list to [{test=1},{test=1}]

I am totally confused why this is happening. Can anyone please explain me ?

Newbie
  • 2,664
  • 7
  • 34
  • 75

2 Answers2

3

You're re-adding the same Map over and over again to the List. You need to create a new one inside of the loop.

    List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>();
    for(int i=0;i<5;i++) {          
        Map<String, Integer> map  = new HashMap<String, Integer>();
        map.put("test", i);
        list.add(map);
    }
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Answered as a community wiki since for sure there is a duplicate question/answer for this common problem. Please help me find the dup and close this question. – Hovercraft Full Of Eels Feb 04 '16 at 03:34
  • this kind of covers it http://stackoverflow.com/questions/19843506/why-does-my-arraylist-contain-n-copies-of-the-last-item-added-to-the-list. The accepted answer has adding the same object as a cause. – George Mulligan Feb 04 '16 at 03:37
  • @GeorgeMulligan: thanks! – Hovercraft Full Of Eels Feb 04 '16 at 03:38
  • @HovercraftFullOfEels Map will be overwritten for same key in each iteration. But I am adding the map to list so list should hold previous map key value pair right ? – Newbie Feb 04 '16 at 03:39
  • @Newbie: makes no sense to do that. Why hold a List that has one entry? – Hovercraft Full Of Eels Feb 04 '16 at 03:40
  • Ok I get it now , there is a single map object and its value changes each time and the list refers to the value in map object and it updates its indices . – Newbie Feb 04 '16 at 03:45
  • @Newbie: There is a single map object. And you added the map object to your list multiple times. So when you output the list, the single map object is displayed multiple times. And since map can only have unique values and also if non unique values are added they will be overwritten, your program shows {test=4} multiple times – Jitin Kodian Feb 04 '16 at 03:49
0

In Map keys are unique and if you try to add elements with same key previous one will be overwritten. Create a new Map in loop and add it to your list.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Yes Map will be overwritten for same key in each iteration. But I am adding the map to list so list should hold previous map key value pair right ? – Newbie Feb 04 '16 at 03:38
  • No `map` i a reference to the actual Map instance. Every time you overwrite it and add it to the list same Map instance gets modified which is reference by all indexes of your List. It's is not like when you add it to your list new Map is created and inserted to list. They are just reference and all point to same Map and change in any will be reflected in other indexes as well. – Aniket Thakur Feb 04 '16 at 04:01