Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

java - Why changes in sublist are reflected in the original list?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As per the JavaDoc on the matter:

List subList(int fromIndex, int toIndex)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

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 locations 0x00 0x01 0x02 which are the same as in original list.

What this means is that if you do sublist.get(0).setFoo(foo), this will in turn seek out the object present at 0x00 and set some property. However, 0x00 is also being referenced to by original 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 through original list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...