操作Arrays.asList的list报UnsupportedOperationException的坑

Arrays.asList()

将数组转换成List集合

    /**
     * Returns a fixed-size list backed by the specified array.  (Changes to
     * the returned list "write through" to the array.)  This method acts
     * as bridge between array-based and collection-based APIs, in
     * combination with {@link Collection#toArray}.  The returned list is
     * serializable and implements {@link RandomAccess}.
     *
     * 

This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: *

     *     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
     * 
* * @param the class of the objects in the array * @param a the array by which the list will be backed * @return a list view of the specified array */
@SafeVarargs @SuppressWarnings("varargs") public static <T> List<T> asList(T... a) { return new ArrayList<>(a); }

Arrays.ArrayList

    /**
     * @serial include
     */
    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);
        }

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

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

        @Override
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) 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<E> spliterator() {
            return Spliterators.spliterator(a, Spliterator.ORDERED);
        }

        @Override
        public void forEach(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            for (E e : a) {
                action.accept(e);
            }
        }

        @Override
        public void replaceAll(UnaryOperator<E> 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<? super E> c) {
            Arrays.sort(a, c);
        }
    }

UnsupportedOperationException

Arrays.asList创建list,当向这个List添加或删除元素时,会报java.lang.UnsupportedOperationException

操作Arrays.asList的list报UnsupportedOperationException的坑_第1张图片

从源码中可知,Arrays.asList创建的ArrayList是Arrays的一个静态内部类,其中add、remove、clear方法都是没有实现的。

那么子类没有实现这些方法,肯定是调用了父类的方法

AbstractList.java

 AbstractList.java
    
    /**
     * {@inheritDoc}
     *
     * 

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(); }

很明显直接抛出UnsupportedOperationException

总结

该方法得到的List的长度是不可变的。当向这个List添加或删除元素时,会报java.lang.UnsupportedOperationException

这里注意一下,set()编辑是可以的

如果你的list只是用来遍历,那么可以用Arrays.asList()获得,但是如果你的list还想用添加、删除方法,那么就要放弃Arrays.asList(),使用new ArrayList的方法获得

你可能感兴趣的:(#,Java8源码,java)