谨慎使用 Arrays.asList() 和 Collections.singletonList()

Arrays.asList() 和 Collections.singletonList() 创建的 List 集合均不能调用其 add 方法(不可变列表),否则会导致 UnsupportedOperationException 报错。

报错原因

Arrays.asList()

查看源码实现:

@SafeVarargs
@SuppressWarnings("varargs")
public static  List asList(T... a) {
    return new ArrayList<>(a);
}

乍一看返回的数据结构没什么问题,实际上这里返回的 ArrayList 是 Array 的内部类,继承自 AbstractList,但是并未实现 add(E e) 方法:

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) {
        E[] a = this.a;
        if (o == null) {
            for (int i = 0; i < a.length; i++)
                if (a[i] == null)
                    return i;
        } else {
            for (int i = 0; i < a.length; i++)
                if (o.equals(a[i]))
                    return i;
        }
        return -1;
    }

    @Override
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    @Override
    public Spliterator spliterator() {
        return Spliterators.spliterator(a, Spliterator.ORDERED);
    }

    @Override
    public void forEach(Consumer 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 void sort(Comparator c) {
        Arrays.sort(a, c);
    }
}

因为该内部类未实现 add 方法,那么就会调用到父类的 add 方法,那么我们来看下父类的实现:

public boolean add(E e) {
    add(size(), e);
    return true;
}

public void add(int index, E element) {
    throw new UnsupportedOperationException();
}

AbstractList#add 方法的实现是直接抛出 UnsupportedOperationException,除非子类复写该方法。

Collections.singletonList()

该接口返回的是 Collections 的内部类 SingletonList,同样继承自 AbstractList,也是未实现 add(E e) 方法

public static  List singletonList(T o) {
    return new SingletonList<>(o);
}

/**
 * @serial include
 */
private static class SingletonList
    extends AbstractList
    implements RandomAccess, Serializable {

    private static final long serialVersionUID = 3093736618740652951L;

    private final E element;

    SingletonList(E obj)                {element = obj;}

    public Iterator iterator() {
        return singletonIterator(element);
    }

    public int size()                   {return 1;}

    public boolean contains(Object obj) {return eq(obj, element);}

    public E get(int index) {
        if (index != 0)
          throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
        return element;
    }

    // Override default methods for Collection
    @Override
    public void forEach(Consumer action) {
        action.accept(element);
    }
    @Override
    public boolean removeIf(Predicate filter) {
        throw new UnsupportedOperationException();
    }
    @Override
    public void replaceAll(UnaryOperator operator) {
        throw new UnsupportedOperationException();
    }
    @Override
    public void sort(Comparator c) {
    }
    @Override
    public Spliterator spliterator() {
        return singletonSpliterator(element);
    }
}

你可能感兴趣的:(谨慎使用 Arrays.asList() 和 Collections.singletonList())