今日调试时,对List进行remove操作时,连续两遍都是抛出了java.lang.UnsupportedOperationException异常,特别奇怪
String[] icarr = ic.split(",");
List<String> iconlist = Arrays.asList(icarr);
int len = iconlist.size();
for (int b = 0; b < len; b++) {
if (icon.equals(ne.get(b))) {
iconlist.remove(b);
break;
}
}
异常在 iconlist.remove(b);这一行,当时很奇怪哈,百度了下,发现是由于asList引起的异常,使用asList返回的是Arrays的内部类ArrayList
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
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) {
a = Objects.requireNonNull(array);
}
她继承的是父类AbstractList里面的add和remove方法只是抛出异常
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
而java.util.ArrayList是这样的
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
他重写了父类的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
解决方法
String[] icarr = ico.split(",");
List<String> iconlist = new ArrayList<>(Arrays.asList(icarr));