asList详解

asList(T... a)返回的是一个固定大小的list集合

源码分析:

public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

此时的ArrayList为Arrays里面自定义的一个私有的内部类

 private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable

其父类AbstractList中事务方法都被禁止了,使用时需要确保返回的list不会去修改。若需要修改可以修改为

 new ArrayList<>(Arrays.asList(T... a));
 public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }

猜你喜欢

转载自blog.csdn.net/qq_34724270/article/details/86534168
今日推荐