java Arrays.asList() 有疑问?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4792160/
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
Arrays.asList() doubt?
提问by Manoj
People say that asList
method convert the array into list and its not copying, so every change in 'aList' will reflect into 'a'. So add new values in 'aList' is illegal, since array have fixed size.
人们说该asList
方法将数组转换为列表而不是复制,因此“aList”中的每个更改都会反映到“a”中。因此,在 'aList' 中添加新值是非法的,因为数组具有固定大小。
But, asList()
method returns ArrayList<T>
. How the compiler differentiates line 3 from 5. Line 3 gives me exception (UnsupportedOperationException
).
但是,asList()
方法返回ArrayList<T>
。编译器如何区分第 3 行和第 5 行。第 3 行给出了异常 ( UnsupportedOperationException
)。
String[] a = {"a","b","c","d"};//1
List<String> aList = Arrays.asList(a);//2
aList.add("e");//3
List<String> b = new ArrayList<String>();//4
b.add("a");//5
回答by Andreas Dolk
This List implementation you receive from Arrays.asList
is a special view on the array - you can't change it's size.
您收到的这个 List 实现Arrays.asList
是数组的一个特殊视图 - 您无法更改它的大小。
The return type of Arrays.asList()
is java.util.Arrays.ArrayList
which is often confused with java.util.ArrayList
. Arrays.ArrayList
simply shows the array as a list.
Arrays.asList()
is的返回类型java.util.Arrays.ArrayList
经常与java.util.ArrayList
. Arrays.ArrayList
简单地将数组显示为列表。
回答by Lie Ryan
Read again, the type of Arrays.asList is:
再读一遍,Arrays.asList的类型是:
public static <T> List<T> asList(T... a)
which clearly states that asList returns an object that implements interface java.util.List, nowhere does it says it will return an instance of class java.util.ArrayList.
它清楚地说明 asList 返回一个实现接口 java.util.List的对象,没有任何地方说它将返回类 java.util.ArrayList的实例。
Next, notice that the documentation on List.addsays:
接下来,请注意List.add上的文档说:
boolean add(E e)
Appends the specified element to the end of this list (optional operation).
布尔加法(E e)
将指定的元素附加到此列表的末尾(可选操作)。
Technically, everytime you use a variable typed as List (instead of ArrayList), you should always be careful to expect that this method may throw UnsupportedOperationException
. If you are sure that you will only receive a List implementation that always have the correct semantic of .add()
, then you can omit the check at the risk of a bug when your assumption is invalidated.
从技术上讲,每次使用类型为 List(而不是 ArrayList)的变量时,您都应该始终小心预期此方法可能会抛出UnsupportedOperationException
。如果您确定您只会收到一个始终具有正确语义的 List 实现.add()
,那么您可以在假设无效时冒着出现错误的风险省略检查。
回答by abhihello123
Manoj,
马诺杰,
The Return type of Arrays.List is some unknown internal implementation of the List interface and notjava.util.ArrayList, so you can assign it only to a List type.
Arrays.List 的 Return 类型是 List 接口的一些未知内部实现,而不是java.util.ArrayList,因此您只能将其分配给 List 类型。
If you assign it to an ArrayList for instance it will give you compile time error "Type mismatch: cannot convert from List to ArrayList"
例如,如果将其分配给 ArrayList,则会出现编译时错误“类型不匹配:无法从列表转换为 ArrayList”
ArrayList<String> aList = Arrays.asList(a);// gives Compile time error
From the Javadoc"Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) " that means that you are only provided a list view of the Array which IMO is created at runtime and ofcourse you cannot change the size of an array so you can't change size of "Arrays.asList" also.
从Javadoc“Arrays.asList 返回由指定数组支持的固定大小列表。(更改返回的列表“写入”到数组。)”这意味着您只提供了 IMO 数组的列表视图是在运行时创建的,当然你不能改变数组的大小,所以你也不能改变“Arrays.asList”的大小。
IMO the internal implementation of Arrays.asList has all the implemented methods which can change the size of the Array as -
IMO Arrays.asList 的内部实现具有所有实现的方法,可以将数组的大小更改为 -
void add(E e)
{
//some unknown code
throw(java.lang.UnsupportedOperationException);
}
so whenever you attempt to alter the size of the Array it throws the UnsupportedOperationException.
因此,每当您尝试更改 Array 的大小时,它都会抛出 UnsupportedOperationException。
Still if you want to add some new items to an ArrayList by using such a syntax, you can do so by creating a subclass of Arraylist(preferably by using anonymous subclass of ArrayList). You can pass the return type of Arrays.List to the constructor of ArrayList, (ie. public ArrayList(Collection c)) something like this -
如果您想使用这样的语法向 ArrayList 添加一些新项目,您可以通过创建 Arraylist 的子类(最好使用 ArrayList 的匿名子类)来实现。您可以将 Arrays.List 的返回类型传递给 ArrayList 的构造函数,(即 public ArrayList(Collection c))像这样 -
List<String> girlFriends = new java.util.ArrayList<String>(Arrays.asList("Rose", "Leena", "Kim", "Tina"));
girlFriends.add("Sarah");
Now you can easily add Sarah to your GF list using the same syntax.
现在,您可以使用相同的语法轻松地将 Sarah 添加到您的 GF 列表中。
PS - Please select this one or another one as your answer because evrything has been explained. Your low Acceptance rate is very discouraging.
PS - 请选择这个或另一个作为您的答案,因为所有内容都已解释。您的低接受率非常令人沮丧。
回答by OrangeDog
asList()
doesn't return a java.util.ArrayList
, it returns a java.util.Arrays$ArrayList
. This class doesn't even extend java.util.ArrayList
, so its behaviour can be (and is) completely different.
asList()
不返回 a java.util.ArrayList
,它返回 a java.util.Arrays$ArrayList
。这个类甚至没有扩展java.util.ArrayList
,所以它的行为可以(并且是)完全不同。
The add()
method is inherited from java.util.AbstractList
, which by default just throws UnsupportedOperationException
.
该add()
方法是从 继承的java.util.AbstractList
,默认情况下它只是抛出UnsupportedOperationException
.
回答by Mihai Toader
It's an exception and not a compiler error. It is thrown when the program is run and not at the compile time. Basically the actual class that Arrays.asList will return has a throw UnsupporteOperationException
inside the add()
method.
这是一个异常,而不是编译器错误。它在程序运行时而不是在编译时抛出。基本上 Arrays.asList 将返回的实际类throw UnsupporteOperationException
在add()
方法内部有一个。
To be more specific Arrays.asList
will return an inner class defined inside the Arrays
class that is derived from AbstractList
and does not implement the add
method. The add
method from the AbstractList
is actually throwing the exception.
更具体地说,Arrays.asList
将返回在Arrays
派生自AbstractList
但不实现该add
方法的类中定义的内部类。中的add
方法AbstractList
实际上是在抛出异常。
回答by Joachim Sauer
You're assuming that Arrays.asList()
returns an ArrayList
, but that's not the case. Arrays.asList()
returns an unspecified List
implementation. That implementaton simply throws an UnsupportedOperationException
on each unsupported method.
您假设Arrays.asList()
返回的是ArrayList
,但事实并非如此。Arrays.asList()
返回一个未指定的List
实现。该实现只是UnsupportedOperationException
在每个不受支持的方法上抛出一个。
回答by Qwerky
The key to this is the List
implementation returned by
关键是List
返回的实现
List<String> aList = Arrays.asList(a);
If you look at the source code in Arrays
you will see that it contains an internal private static class ArrayList
. This is not the same as java.util.ArrayList
.
如果您查看 中的源代码,Arrays
您将看到它包含一个内部私有静态类ArrayList
。这与java.util.ArrayList
.
回答by sinelaw
asList returns a fixed-size list, so that you cannot add new elements to it. Because the list it returns is really a "view" of the array it was created from ('a' in your case), it makes sense that you won't be able to add elements - just like you can't add elements to an array. See the docs for asList
asList 返回一个固定大小的列表,因此您不能向其中添加新元素。因为它返回的列表实际上是从它创建的数组的“视图”(在您的情况下为'a'),所以您将无法添加元素是有道理的 - 就像您无法向其中添加元素一样数组。请参阅asList的文档