Author: I want to ask days juejin. Im/post / 5 d10e52ee51d454f6f16ec11

The Alibaba Java development specification says that when you use the arrays.aslist () utility class to convert Arrays to collections, you can’t use it to modify collection related methods.

Because it came to the add/remove/clear method throws an UnsupportedOperationException (), let’s take a look at why this happens.

Problem analysis

Let’s take a test:

public static void main(String[] args) {
       List<String> list = Arrays.asList("a", "b", "c");
       // list.clear();
       // list.remove("a");
       // list.add("g");
}Copy the code

The annotated three lines can be uncommented separately, and the run does produce the exception described in the specification. Let’s take a look at what arrays.aslist () does.

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

It looks like a normal method, but in fact when you click on an ArrayList, it turns out that an ArrayList is not an ArrayList.

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

It’s an inner class of Arrays.

And this inner class doesn’t have add, clear, and remove methods, so the exception actually comes from AbstractList.

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

public E remove(int index) {
      throw new UnsupportedOperationException();
}Copy the code

Click on it to see where the exception was thrown, and the bottom layer of clear will also call remove so it will throw an exception.

conclusion

1. Arrays.aslist ()

If arrays.aslist () is used, it’s probably best not to use its collections.

List List = new ArrayList<>(array.asList (“a”, “b”, “c”))

There are many ways to convert an array to a collection.

Stackoverflow.com/questions/1…

Read more on my blog:

1.Java JVM, Collections, Multithreading, new features series tutorials

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA series tools tutorial

4.Java, backend, architecture, Alibaba and other big factory latest interview questions

Life is good. See you tomorrow