数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException

时间:2023-03-09 17:12:10
数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException

Java中,可以使用Arrays.asList(T... a)方法来把一个数组转换为List,返回一个受指定数组支持的固定大小(注意是固定大小)的列表。此方法同 Collection.toArray()一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。

此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:

List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

当转换后,使用add或者remove方法总是抛出java.lang.UnsupportedOperationException异常。

其底层的实现代码如下:

public static <T> List<T> asList(T... a) {

return new ArrayList<T>(a);

}

创建了一个ArrayList对象,而这个ArrayList并不是java.util包下面的ArrayList,而是java.util.Arrays类中的一个内部类,其实现代码如下:

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;

}

而这个ArrayList类又继承了AbstractList类,其中的add和remove方法的实现过程又如下:

public void add(int index, E element) {

throw new UnsupportedOperationException();

}

public E remove(int index) {

throw new UnsupportedOperationException();

}

为什么要直接抛出异常呢?注意是固定大小的list 所以就直接抛异常,不让你用

所以,肯定为出现不支持操作的异常。

那么,一种解决办法是把列表再拷贝到ArrayList中就好了。

ArrayList newList = new ArrayList<>(list);就可以使用add()和remove()方法了。

或newList.addAll(list);