java.lang.UnsupportedOperationException

今天在写项目时遇到这个错: java.lang.UnsupportedOperationException,着时有点纳闷啊,因为是ArrayLiat的addAll操作,原则上是没问题的。那么问题是在哪里,看看下面的代码:

import java.util.Arrays;

List selectedImagePath= new ArrayList<>();
if (!TextUtils.isEmpty(maintainBean.local_photo_array)) {
        selectedImagePath.clear();
            // 字符串转字符数组
        String[] localItemPhoto = maintainBean.local_photo_array.split(",");
        selectedImagePath=Arrays.asList(localItemPhoto);
}

//源码如下--Arrays.java:

    /**
     * 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 List asList(T... a) { return new ArrayList<>(a); }

从源码上面发现Arrays.asList(localItemPhoto),返回由指定数组支持的固定大小列表,该方法与{@link Collection#to Array}相结合,充当基于数组和基于集合的API之间的桥梁.那么这里返回的ArrayLiat和java本身的Arraylist有什么不同?继续看下源码发现new ArrayLiat<>(a)调用了 ArrayList(E[] array) {  a = Objects.requireNonNull(array);  },沮洳实现如下:没深入研究,到这里差不多指导问题是什么了.这里返回的ArrayLiat是Arrays的内部类,不是我们需要的"ArrayList",我们需要的list是collection的子类,ArrayLiat是List的具体实现.

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

而这里Arrays返回的ArrayLiat是arrays的内部类,且没有AddAll方法,也没有你 remove方法.那么ArrayListAddAll方法,也没有你 remove方法.在哪里.我们继续找下集合的顶层父类collection中查看.

   /**
     * Adds all of the elements in the specified collection to this collection
     * (optional operation).  The behavior of this operation is undefined if
     * the specified collection is modified while the operation is in progress.
     * (This implies that the behavior of this call is undefined if the
     * specified collection is this collection, and this collection is
     * nonempty.)
     *
     * @param c collection containing elements to be added to this collection
     * @return true if this collection changed as a result of the call
     * @throws UnsupportedOperationException if the addAll operation
     *         is not supported by this collection
     * @throws ClassCastException if the class of an element of the specified
     *         collection prevents it from being added to this collection
     * @throws NullPointerException if the specified collection contains a
     *         null element and this collection does not permit null elements,
     *         or if the specified collection is null
     * @throws IllegalArgumentException if some property of an element of the
     *         specified collection prevents it from being added to this
     *         collection
     * @throws IllegalStateException if not all the elements can be added at
     *         this time due to insertion restrictions
     * @see #add(Object)
     */
    boolean addAll(Collection c);

在这里找到了addAll()方法,惊喜的发现"UnsupportedOperationException if the addAll operation  is not supported by this collection"原来是当前集合不支持该操作,到这里已经找到问题所在了,那么怎么解决:

1.我猜使用构造函数创建一个新的Arraylist,并将Arrys返回的list作为参数传递给Arraylist的构造函数,不知道能行与否,于是查看下Arraylist的源码,发现了下面的方法

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

于是我就将代码按照这个格式进项改造下:

List selectedImagePath= new ArrayList<>();
if (!TextUtils.isEmpty(maintainBean.local_photo_array)) {
        selectedImagePath.clear();
            // 字符串转字符数组
        String[] localItemPhoto = maintainBean.local_photo_array.split(",");
        selectedImagePath = new ArrayList<>(Arrays.asList(localItemPhoto)) ;
}

运行,问题解决;后面想来下下面的代码应该也是可以的,没验证:

 if (!TextUtils.isEmpty(maintainBean.local_photo_array)) {
            selectedImagePath.clear();
            // 字符串转字符数组
            String[] localItemPhoto = maintainBean.local_photo_array.split(",");
            selectedImagePath.addAll(Arrays.asList(localItemPhoto));
           
}

到此,问题解决了.开心.可能有不对的地方,希望给与指正,谢谢!

你可能感兴趣的:(Android)