Java ArrayList 与 Arrays.asList() 返回的 List

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25729553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:01:00  来源:igfitidea点击:

ArrayList vs the List returned by Arrays.asList()

javaarrayslistarraylist

提问by Roam

The method Arrays.asList(<T>...A)returns a Listrepresentation of A. The returned object here is a Listbacked by an array, but is not an ArrayListobject.

该方法Arrays.asList(<T>...A)返回 的List表示A。这里返回的对象是一个List由数组支持的ArrayList对象,但不是一个对象。

I'm looking for the differences between the object Arrays.asList()returns and an ArrayListobject-- a quick source to tell these without diving into the code.

我正在寻找对象Arrays.asList()返回和对象之间的差异 -ArrayList一个快速来源,无需深入代码即可告诉这些。

TIA.

TIA。

采纳答案by SparkOn

When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayListwhich is a fixed size list backed by the original source array. In other words, it is a view for the array exposed with Java's collection-based APIs.

当您调用 Arrays.asList 时,它不会返回java.util.ArrayList. 它返回一个java.util.Arrays$ArrayList由原始源数组支持的固定大小列表。换句话说,它是使用 Java 的基于集合的 API 公开的数组的视图。

    String[] sourceArr = {"A", "B", "C"};
    List<String> list = Arrays.asList(sourceArr);
    System.out.println(list); // [A, B, C]

    sourceArr[2] = ""; // changing source array changes the exposed view List
    System.out.println(list); //[A, B, ]

    list.set(0, "Z"); // Setting an element within the size of the source array
    System.out.println(Arrays.toString(sourceArr)); //[Z, B, ]

    list.set(3, "Z"); // java.lang.ArrayIndexOutOfBoundsException
    System.out.println(Arrays.toString(sourceArr));

    list.add("X"); //java.lang.UnsupportedOperationException

    list.remove("Z"); //java.lang.UnsupportedOperationException

You cannot add elements to it and you cannot remove elements from it. If you try to add or remove elements from them you will get UnsupportedOperationException.

您不能向其中添加元素,也不能从中删除元素。如果您尝试在其中添加或删除元素,您将获得UnsupportedOperationException.

回答by Maroun

I'll expand my comment a little bit.

我会稍微扩展一下我的评论。

One problem that can occur if you use asListas it wasn't different from ArrayListobject:

如果您使用asList它,可能会出现一个问题,因为它与ArrayList对象没有区别:

List<Object> list = Array.asList(array) ;
list.remove(0); // UnsupportedOperationException :(

Here you cannot remove the 0 element because asListreturns a fixed-size list backed by the specified array. So you should do something like:

在这里您不能删除 0 元素,因为asList返回由指定数组支持固定大小列表。所以你应该做这样的事情:

List<Object> newList = new ArrayList<>(Arrays.asList(array));

in order to make the newListmodifiable.

为了使newList可修改。