UnsupportedOperationException异常分析

486 阅读1分钟

UnsupportedOperationException

今天做需求中使用了Arrays.asList()方法,生成一个List,并用生成的List做了add操作,出现了这个操作

类似于下面的操作

    List<String> list = Arrays.asList("aaa", "bbb", "ccc");
    list.add("ddd");

结果出现了 UnsupportedOperationException 异常

字面分析是不支持的操作异常,分析一共就两个操作,肯定就是add操作出现了异常

但是接口List的add操作有很多实现类,从上面两端代码无法看出add的是实现类是哪一个

先进入asList() 方法

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

可以看到返回一个newArrayList<> 但是根据常识我们知道java.util中的ArrayList类,也就算我们常用的那个ArrayList类并不支持传入多参数的构造方法,因此点进去这个构造方法,我们就发现这是Arrays自己实现的一个内部类

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

完成代码就不展示了

这个类依旧继承了 AbstractList 抽象类

重点就是这个类的add方法并没有重写父类 AbstractList 的add方法,而是沿用了 AbstractList 的 add 方法,进入底层可以看到 AbstractList 的 add 方法抛出了 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();
    }

总结来说就是 Arrays.asList() 方法返回了一个内部类 ArrayList ,这个内部类ArrayList 沿用了 父类AbstractList 的 add 方法,抛出了一个 UnsupportedOperationException