I have recently come across a weird 'feature' in java that means ArrayLists seem to magically have items added to them when I add items to a different list. See below:
List<Integer> i = new ArrayList<Integer>();
List<Integer> i2 = i;
i.add(77);
System.out.println(i);
System.out.println(i2);
This program gives the output:
[77]
[77]
However, if you replace the lists with just integers:
int i = 5;
int i2 = i;
i = 7;
System.out.println(i);
System.out.println(i2);
It works as I would expect giving the result
7
5
Why does this happen and how can I stop i
and i2
becoming the same list when I do i.add()
?