问题描述
我知道 Java 中的 Collections
在您通过引用传递它们时是可变的.
我想确切地知道它的原始列表和子列表的内存地址中发生了什么.
子列表和原始列表指向同一个对象吗?
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);
推荐答案
根据 JavaDoc
关于此事:
As per the JavaDoc
on the matter:
List subList(int fromIndex,int toIndex)
返回此列表中指定的 fromIndex、inclusive 和 toIndex 之间的部分的视图,独家的.(如果 fromIndex 和 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.
根据您的评论,假设 original list
具有以下引用:0x00 0x01 0x02 0x03 0x04 0x05
并且这些映射到内存中存在对象的位置.
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.
在上面执行 sublist(0, 2)
将产生一个列表,其中包含指向以下内存位置 0x00 0x01 0x02
的指针,这些位置与 中的相同>原始列表
.
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
.
这意味着如果你执行 sublist.get(0).setFoo(foo)
,这将依次寻找 0x00
处的对象并设置一些财产.但是,0x00
也被 original list
引用,这就是为什么更改子列表意味着您将更改源列表 ,因为两个列表都指向相同的对象.如果您通过 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
.
这篇关于为什么子列表的变化会反映在原始列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!