如果我更改传递给Arrays.asList(array)的数组,则列表值也会更改 [英] List values change if I change the array passed to Arrays.asList(array)

查看:67
本文介绍了如果我更改传递给Arrays.asList(array)的数组,则列表值也会更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了Arrays.class代码,但是即使下面的代码返回了新的ArrayList,也无法理解为什么对数组所做的更改会反映到ArrayList中.

I have seen the code Arrays.class, but not able to understand why the changes made to the array is reflecting to ArrayList even though below code returns new ArrayList.

@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

示例代码:

    public class Test {
    public static void main(String[] args) {
        Integer [] array = {1,2,3,4,5};
        List<Integer> list = new ArrayList<>();
        list = Arrays.asList(array);
        System.out.println("List created from array:  " + list);
        array[0] = 100;
        System.out.println("List after changing array:" + list);
    }
}

输出:

从数组创建的列表:[1、2、3、4、5]

List created from array: [1, 2, 3, 4, 5]

更改数组后的列表:[100、2、3、4、5]

List after changing array:[100, 2, 3, 4, 5]

推荐答案

该列表由有关

返回由指定数组支持的固定大小的列表. (更改为 返回的列表直写"到数组.)

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

如果您挖出return new ArrayList<>(a)行,您将看到:

And if you digging the line return new ArrayList<>(a) you will see:

private final E[] a; // This is internal array of List

ArrayList(E[] array) {
    a = Objects.requireNonNull(array);
}

public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj; // Just return the array reference. No deep copy
}

如您所见,列表不会复制数组数据,只是将其引用分配给其内部数组.

So as you can see, the list does not copy the array data, just assign it reference to its internal array.

因此,对原始数组的更改会反映在列表中,反之亦然

Hence your change to original array is reflected to the list and vice versa

请注意:Arrays.asList()返回Arrays.ArrayList<>的实例:

private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, java.io.Serializable {
}

java.util.ArrayList不同,由Arrays.asList返回的List不能实现所有List函数.如果尝试使用add()之类的方法,它将抛出UnsupportedOperationException

Unlike java.util.ArrayList, the List returned by Arrays.asList does not implement all of List functions. If you try to use methods like add(), it will throw UnsupportedOperationException

这篇关于如果我更改传递给Arrays.asList(array)的数组,则列表值也会更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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