I know that Collections
in Java are mutable when you pass them through references.
I want to know exactly what happens in memory addresses of original-list and sublist/s of it.
Do the sublist and original list refer to the same object?
Following is code sample reflecting changes made in sublist to main original list.
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add(1, "3");
List<String> list2 = new LinkedList<String>(list);
list.addAll(list2);
list2 = list.subList(2, 5);
list2.clear(); //Changes are made to list
System.out.println(list);
In line
you are calling
subList
method ofArrayList
referred fromlist
. Its code looks like thisso after confirming valid range list2 will store result of
where
private class SubList extends AbstractList<E>
is class defined insideArrayList
and code of this constructor looks like thisso its
parent
field will store reference to originalArrayList
(new SubList(this, ...)
).Now when you call
code of
clear()
method inherited bySubList
fromAbstractList
will be invokedwhich will internally invoke
removeRange
overridden inSubList
So as you see, as result you are calling
where as you remember
parent
holds reference to ArrayList on whichsubList
was called. So effectively by callingclear
you are invokingremoveRange
from original list from which you created sublist.Check this link.
So your list2 is just a sub-view of your orginal list.That is why, when you are clearing list2, you are losing corresponding values in orginal list.Check this code.
O/P
As per the
JavaDoc
on the matter:The sub list will point to the same elements present within the original list, thus, any changes made through the sub list will be reflected within the original list since you are changing the same objects.
EDIT: As per your comment, assume that the
original list
has the following references:0x00 0x01 0x02 0x03 0x04 0x05
and these map to locations in memory where objects exist.Doing
sublist(0, 2)
on the above will yield a list which contains pointers to the following memory locations0x00 0x01 0x02
which are the same as inoriginal list
.What this means is that if you do
sublist.get(0).setFoo(foo)
, this will in turn seek out the object present at0x00
and set some property. However,0x00
is also being referenced to byoriginal list
, which is why changing the sub list means that you will be changing the source list since both lists point to the same objects. The same also holds should you change your elements throughoriginal list
.