UnsupportedOperationException

AsList () method is used to generate a List and add the generated List. This operation occurs

Similar to the following

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

The results appeared abnormal UnsupportedOperationException

Literal analysis is an unsupported operation exception. There are only two operations in the analysis, so it must be the ADD operation that has an exception

However, the interface List add operation has many implementation classes, from the above two ends of the code can not see which implementation class add is

Let’s go to the asList() method

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

You can see that it returns a newArrayList<> but it’s common sense to know that the ArrayList class in Java.util, even though our usual ArrayList class doesn’t support passing in a multi-argument constructor, so if you click on this constructor, We realize that this is an inner class of Arrays that implements itself

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

I won’t show you the finished code

This class still inherits the AbstractList abstract class

The point is that this class doesn’t override AbstractList’s add method, but uses AbstractList’s add method. Into the underlying can see the add method of AbstractList throw UnsupportedOperationException anomalies

    / * * * {@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();
    }
Copy the code

The ArrayList () method returns an inner ArrayList class that follows the add method of its parent, AbstractList. Throws an UnsupportedOperationException