List 操作add 报错

操作List报java.lang.UnsupportedOperationException

2018.03.12 16:52:01字数 230阅读 1683

问题描述

 

 

 

 

 

 

 

今天在项目中调用List的add(..)方法时,程序报了java.lang.UnsupportedOperationException,这个List并非是List list = new ArrayList()而来,而是用Arrays.asList(..)得到的:

List<String> list = Arrays.asList("test1", "test2", "test3");
list.add("test4");

运行结果:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at Main.main(Main.java:8)

原因分析

跟进到asList(..)方法的源码中:

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

坑就在这里,它返回的这个ArrayList并不是java.util.ArrayList<E>,而是java.util.Arrays的内部类。

 


这两个ArrayList都继承自AbstractList<E>,跟进到AbstractList<E>里面看源码:

 

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

可以看出父类中的set,add,remove方法都是直接抛出UnsupportedOperationException,再回到Arrays的内部类ArrayList,并没有去重写上述方法,因此使用List.asList(..)返回的Arrays内部类ArrayList对象进行add等操作时会抛此异常。再看java.util.ArrayList<E>中,都是对上诉方法进行了重写,因此通过new ArrayList()得到的List进行add等操作,不会有问题。


解决方法

很简单:

List<String> list = new ArrayList<>(Arrays.asList("test1", "test2", "test3"));
list.add("test4");
posted @ 2019-10-24 15:24  abcdefghijklmnop  阅读(1281)  评论(0编辑  收藏  举报