为什么子列表中的更改会反映在原始列表中? [英] Why changes in sublist are reflected in the original list?

查看:126
本文介绍了为什么子列表中的更改会反映在原始列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道当你通过引用传递它们时,Java中的集合是可变的。

我想确切地知道原始内存地址中发生了什么-list和sublist / s。

子列表和原始列表是否指向同一个对象?

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:


列出subList(int fromIndex,
int toIndex)

List subList(int fromIndex, int toIndex)

返回指定fromIndex(包含)和toIndex(
exclusive)之间此列表部分的视图。 (如果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.

编辑:按照您的评论,假设原始列表具有以下参考: 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.

在上面做子列表(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 也被原始列表引用,这就是为什么更改子列表意味着你将成为更改源列表,因为两个列表都指向相同的对象。如果您通过原始列表更改元素,也同样如此。

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.

这篇关于为什么子列表中的更改会反映在原始列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆