Arrays.asList();通过该方法返回的List做删除以及添加会报错nested exception is java.lang.UnsupportedOperationException

解决办法: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


版权声明:本文为qq_29417111原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。