Its probably a very simple one but its' still confusing me!
import java.util.ArrayList;
public class Sample {
ArrayList<Integer> i = new ArrayList<>();
ArrayList<Integer> j = new ArrayList<>();
/**
* @param args
*/
public static void main(String[] args) {
new Sample().go();
}
private void go() {
i.add(1);
i.add(2);
i.add(3);
j=i;
i.remove(0);
System.out.println(i + "asd" + j);
}
}
I tried to print it :
[2, 3]asd[2, 3]
Why does j change when i changes? Does not happen with primitives though!
The Object is not cloned, just an additional object reference has been added. Since ArrayList is not immutable, any change to the object is reflected in both the object references.
Let me do this in the following way for you:
compare both the values if they are same that means after
j=i;
ArrayList j
is now pointing toArrayList i
In my machine o/p was:
The statement
j=i;
assigns the referencej
to be the same reference asi
. Now bothi
andj
refer to the sameArrayList
object. The removal of the 0th index is simply visible through both references.If you would like the removal of an item in
i
not to affect the list fromj
, then create a copy of the list, instead of assigning the references:(It's a shallow copy, so the lists still refer to the same elements.)
You created a memory stage for j with ; j = new ArrayList<>();
but then you said that let j refer to i's memory stage. So after j=i; any changes on i or j are going to effect both of them. Because they reference to the same objects.
Objects and primitives work somewhat differently. Think of an object like
i
as being the name of that object. When you sayj=i
you're telling the JVM "forget about that otherArrayList
that I said was calledj
; from now on when I refer toj
, I mean thisArrayList
that can also be calledi
. And indeed, that's exactly what happened: after that line, both variables refer to the same object.Primitives work as you say. If you say
i=5; j=i; i=6
, thenj
will still be set to 5.Use
or
to create a copy.
With
j = i
you only makej
point oni
(it's called reference). This applies to all assignments that involve objects (not primitive types likeint
orfloat
)