0

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()?

  • 7
    They don't become the same list when you do `i.add()`, they were *always* the same list. There's no magic here; `i2 = i` **does not** create a copy. – jonrsharpe Feb 24 '20 at 21:06
  • 1
    To add more info, the correct way to make a copy would be `List i2 = new ArrayList<>(i);`. – Nexevis Feb 24 '20 at 21:07

1 Answers1

0

Primitives like int behave differently from objects like ArrayList in this respect. Using = with a primitive will produce a duplicate of the primitive, whereas doing so with an object will give you the same object. If you then try to mutate the object (for example, .add()), then the object will be mutated, and both of the variables referencing it will be able to see that.

To make a 'soft copy' (a different list containing the same elements), you can call ArrayList's constructor with an existing ArrayList:

List<Integer> i = new ArrayList<>();
List<Integer> i2 = new ArrayList<>(i);
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53