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 ?