Why Ali Statute manual method requires careful use Arrays.asList

Foreword

In development, sometimes encountered multiple parameters, or to turn into a List array of needs, we would usually use Arrays.asList () method. However, the method used in the process, the slightest mistake will seriously abnormal. We have the following code:

@Test
public void test() {
    List<String> list = Arrays.asList("a", "a", "2");
    System.out.println(list.size());

    list.add("blog.happyjava.cn");
    System.out.println(list.size());
}
复制代码

After the operation, there has been an exception:

Ali mandatory requirement in the statute Java

Ali Java has a mandatory requirement in the statute: the use of tools Arrays.asList () when the array into a collection, you can not use it to amend the relevant set of methods, it's add / remove / clear method throws UnsupportedOperationException exception.

Ali Statute already prompted the return of the object asList is an internal class Arrays of. Well, this inner class, now we generally use the List (such as ArrayList) what is the same place it, here we have to analyze.

Arrays.asList () source code analysis

IDEA by viewing the source code method, as follows:

Here returns a ArrayList, seems to be no problem, but this ArrayList with our usual java.util.ArrayList not the same. Hit the jump by IDEA, you can see this is an internal ArrayList class Arrays of.

The inner class source code is actually not much, by the structure IDEA, we can see that it implements the following method:

You can see, this is not achieved we add the most commonly used method.

Then, add other methods of calling time, UnsupportedOperationException where an exception is thrown out of it? We look at it inherits java.util.AbstractList class, add the class method as follows:

public boolean add(E e) {
    add(size(), e);
    return true;
}
复制代码

There add an overloaded method, and then point into view:

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

It can be seen here throws UnsupportedOperationException.

to sum up

Arrays.asList () is a very common method development, so we must understand the pit of its existence. If it returns an ArrayList as our common java.util.ArrayList, it is very easy to lay production risks.

Guess you like

Origin juejin.im/post/5d0cdc0751882532cf35e245