List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
当转换后,使用add或者remove方法总是抛出java.lang.UnsupportedOperationException异常。
查看源代码,可知
// Misc
/**
* 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 a the array by which the list will be backed
* @return a list view of the specified array
*/
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
创建了一个ArrayList对象,而这个ArrayList并不是java.util包下面的ArrayList,而是java.util.Arrays类中的一个内部类,继续查看底层代码可知:
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
其继承了AbstractList类,而AbstractList中AbstractList的add和remoce方法实现为 public void add(int index, E element) {
throw new UnsupportedOperationException();
}
其中一种解决办法是把列表再拷贝到ArrayList中:
ArrayList newList = new ArrayList<>(list);
就可以使用add()和remove()方法了。