ArrayList vs Arrays.ArrayList
在一次部署中,发现如下代码竟然抛出来了UnsupportedException
List<String> srcList = Arrays.asList(new String[]{"a", "b", "c"})
List<String> toRemoveList = srcArrays.asList(new String[]{"a", "b"})
srcList.removeAll(toRemoveList)
点进去Arrays.asList
方法,发现返回的是new ArrayList(a)
啊。但是发现返回的是Arrays的内部类ArrayList
,并非我们常用java.util.ArrayList
.
内部类ArrayList
继承了AbstractList
类,但是没有实现remove
接口,所以在removeAll
的时候就会抛异常。
附上Arrays.asList
的doc
/**
* 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 {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
* </pre>
*
* @param <T> the class of the objects in the array
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/