美文网首页
关于调用List的remove方法抛出unsupportedOp

关于调用List的remove方法抛出unsupportedOp

作者: 攻城虱小马褂 | 来源:发表于2021-09-27 09:19 被阅读0次

Background

最近在使用List的remove方法抛出了UnsupportedOperationException异常,在网上查询了相关资料之后,把这部分内容总结下来以供学习

case

    @Test
    public void test7()throws Exception{
        String[] testArr = {"Tom","Jerry","Dave"};
 
        List<String> strList = Arrays.asList(testArr);
 
        strList.remove("Tom");
 
        System.out.println(strList);
 
    }

Exception

java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(AbstractList.java:161)
    at java.util.AbstractList$Itr.remove(AbstractList.java:374)
    at java.util.AbstractCollection.remove(AbstractCollection.java:293)
    at com.synnex.order.search.service.dao.DemoTest.test7(DemoTest.java:140)

我们查看Arrays.asList方法的源码

public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }
 
    /**
     * @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);
        }
    }
private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable

由源码可以发现:

(1)重新new了一个ArrayList, 但是这个ArrayList不是来自于util包下面的ArrayList, 而是Arrays类里面的内部静态类,

 (2)这个内部静态类继承AbstractList, 但是没有重写add() , remove()等方法, 所以在调用add(). remove()等方法的时候,实际调用的是AbstractList类的add()和remove()的方法

查看AbstractList源码:

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

由此, 通过会抛出UnsupportedOperationException异常。

解决方案

String[] testArr = {"Tom","Jerry","Dave"};
        
List<String> stringList = new ArrayList<String>(Arrays.asList(testArr));
 
stringList.remove("Tom");
 
System.out.println(stringList);

可以通过Arrays.asList方法结果传入util类的ArrayList的构造方法, 最终调用add(), remove()的方法是调用的util类的add(), remove方法。

public ArrayList(Collection<? extends E> 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;
        }
    }

总结

 (1)Array.asList返回的List没有重写add(), remove()等方法,调用时是直接调用AbstarctList的方法,由此会抛出异常

 (2)可以将Array.asList的结果作为参数,传入ArrayList的构造方法,通过ArrayList(Collection c)的构造方法可以看出,只是获取了集合c的元素内容,重新组装了一个util类的ArrayList。由此,就可以正常调用add(), remove()方法

相关文章

网友评论

      本文标题:关于调用List的remove方法抛出unsupportedOp

      本文链接:https://www.haomeiwen.com/subject/gkgyjltx.html