解决办法:new ArrayList<>(Arrays.asList());此时返回的List则可以正常添加与移除。
今天在做数组的求交集,当时把String[]转换成List<String>,通过Arrays.asList进行转换,当两个list做retainAll操作时候,抛出了异常“java.lang.UnsupportedOperationException”
发生原因:使用asList返回的是Arrays的内部类ArrayList,继承的是父类AbstractList里面的add和remove方法只是抛出异常
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
而java.util.ArrayList是重写了父类的add和remove方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
所以原因就在于,使用asList方法放回的继承的父类的add和remove,就只会抛出UnsupportedOperationException异常,java.util.ArrayList重写了父类的add和remove