The following code outputs
[[100, 200, 300], [100, 200, 300]].
However, what I expect is
[[100, 200, 300], [100, 200]],
The command outer.add(inner)
adds a reference to inner
, not a copy of it.
So, when you add two references to inner
to the ArrayList outer
, you're adding two of the same thing. Modifying inner
through outer.get(0)
also modifies the value in outer.get(1)
, because they refer to the same thing.
If you create a copy of inner
and use that instead, then you'll have two different instances and be able to modify them separately. You can do this with a simple command:
outer.add(new ArrayList<[var type]>(inner));
The instruction for new ArrayList(inner)
creates a new ArrayList
with the contents of inner
inside of it - but doesn't use the same instance as inner
. Thus, you'll retain the content, but not retain the duplicated reference.
By adding the new copy instead of the reference, you can modify the copy without modifying what you might call the "original."