[英]Created two Lists from same array, Modifying one List, changes the other
I created two list from same array and sorted one of them. 我从同一个数组创建了两个列表并对其中一个进行了排序。 When I tried to change one list, other list also got updated.
当我尝试更改一个列表时,其他列表也已更新。
List<Integer> list = Arrays.asList(ar);
List<Integer> sorted = Arrays.asList(ar);
Collections.sort(sorted);
list.set(0,10000000); //changes sorted also
It took me a while figure out, below mentioned code worked. 我花了一段时间才弄明白,下面提到的代码工作了。
List<Integer> sorted = new ArrayList<Integer>(Arrays.asList(ar));
I want to know why my first approach didn't work? 我想知道为什么我的第一种方法不起作用? I created two separate lists, why the changes are taking place in both of them.
我创建了两个单独的列表,为什么这两个列表都发生了变化。 How does java assign values to variables here?
java如何在这里为变量赋值?
From the Java documentation for Arrays.asList
: 从
Arrays.asList
的Java文档:
Returns a fixed-size list backed by the specified array.
返回由指定数组支持的固定大小的列表。 (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with
Collection.toArray()
.(对返回列表的更改“直写”到数组。)此方法与
Collection.toArray()
结合,充当基于数组的API和基于集合的API之间的桥梁。 The returned list is serializable and implementsRandomAccess
.返回的列表是可序列化的并实现
RandomAccess
。
So when you change something in list, it "writes through" to the underlying array, ar
, which is also the underlying array in sorted, so the change is reflected in sorted as well. 因此,当您更改列表中的某些内容时,它会“写入”到底层数组
ar
,这也是已排序的基础数组,因此更改也会反映在已排序中。
Also, the code for asList
is: 此外,
asList
的代码是:
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
This is java.util.Arrays.ArrayList
, which has the following definition: 这是
java.util.Arrays.ArrayList
,它具有以下定义:
ArrayList(E[] array) {
a = Objects.requireNonNull(array);
}
What is important is that a
is not copied, it is the original array. 重要的是
a
不复制,它是原始数组。 The java.util.ArrayList
class has the following constructor java.util.ArrayList
类具有以下构造函数
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
so in the java.util.ArrayList
constructor, we create copies of each element, and in java.util.Arrays.ArrayList
, we do not. 所以在
java.util.ArrayList
构造函数中,我们创建了每个元素的副本,而在java.util.Arrays.ArrayList
,我们没有。
Arrays有自己的ArrayList实现,它不会从toList复制数组
A List is a collection of objects, and both list are collections of the same objects. List是对象的集合,两个列表都是相同对象的集合。 The set statement changes an object, and the object is shared by both lists.
set语句更改了一个对象,该对象由两个列表共享。
I don't understand why the second version works. 我不明白为什么第二个版本有效。
list和sorted仍然指向第一种方法中的ar的相同内存地址,而在第二种方法中,在调用构造函数之后已经分配了新的内存地址,新的内存块被分配给类对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.