Arrays.asList 转换数组后add或remove出现java.lang.UnsupportedOperationException异常

 

String[] array = {"a","b","c"};
List list = Arrays.asList(array);
list.add("d");
list.remove(0);

 

add或remove时抛出java.lang.UnsupportedOperationException异常的原因是因为,Arrays.asList()方法返回的对象是Array内部类ArrayList对象(而不是java.util.ArrayList的对象),而这个内部类继承了AbstractList类,但是并未实现add和remove方法,AbstractList类中的add和remove方法默认会throw UnsupportedOperationException

这就是抛出java.lang.UnsupportedOperationException异常的原因。源码如下:

Array内部类ArrayList源码:

private static class ArrayList extends AbstractList
    implements RandomAccess, java.io.Serializable
{
    private static final long serialVersionUID = -2764017481108945198L;
    private final E[] a;

    ArrayList(E[] array) {
        a = Objects.requireNonNull(array);
    }

    @Override
    public int size() {
        return a.length;
    }

    @Override
    public Object[] toArray() {
        return a.clone();
    }

    @Override
    @SuppressWarnings("unchecked")
    public  T[] toArray(T[] a) {
        int size = size();
        if (a.length < size)
            return Arrays.copyOf(this.a, size,
                                 (Class) a.getClass());
        System.arraycopy(this.a, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    @Override
    public E get(int index) {
        return a[index];
    }

    @Override
    public E set(int index, E element) {
        E oldValue = a[index];
        a[index] = element;
        return oldValue;
    }

    @Override
    public int indexOf(Object o) {
        if (o==null) {
            for (int i=0; i action) {
        Objects.requireNonNull(action);
        for (E e : a) {
            action.accept(e);
        }
    }

    @Override
    public void replaceAll(UnaryOperator operator) {
        Objects.requireNonNull(operator);
        E[] a = this.a;
        for (int i = 0; i < a.length; i++) {
            a[i] = operator.apply(a[i]);
        }
    }

    @Override
    public Spliterator spliterator() {
        return Spliterators.spliterator(a, Spliterator.ORDERED);
    }
}
AbstractList部分源码:(为了方便看,我把和此处不相关的代码和注释然去掉了)
public abstract class AbstractList extends AbstractCollection implements List {
   
    protected AbstractList() {
    }
    public boolean add(E e) {
        add(size(), e);
        return true;
    }
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }
}

 

你可能感兴趣的:(笔记,Android)