运行时将会发现提示:UnsupportedOperationException的异常。
通过源码我们发现,Arrays.asList()方法返回的ArrayList继承自AbstractList,同时实现了RandomAccess和Serializable接口。
问题就出在这里。这个ArrayList不是java.util包下的,而是java.util.Arrays.ArrayList,显然它是Arrays类自己定义的一个内部类!这个内部类没有实现add()、remove()方法,而是直接使用它的父类AbstractList的相应方法。
那我们接着看这个AbstractList,定义如下:
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
我们再来看一下里面的set,add,remove方法,定义如下:
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
全都返回了这个异常。
总结:Arrays.asList()返回的ArrayList继承自AbstractList,它仅支持那些不会改变数组大小的操作,所以任何对底层数据结构的尺寸进行修改的方法都会出现异常,Arrays.asList()返回固定尺寸的List。
那么如何才能避免这个错误呢?
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));
thinking in java给的解释是:把Arrays.asList()的结果作为构造器的参数传递给任何Collection。