Tools Arrays.asList () method of the array into a set of

Tools Arrays.asList () method of the array into a set of

You can not use its associated methods to modify the collection, it's add / remove / clear method throws UnsupportedOperationException ()

Analysis :

1 , the test

 

 

Annotated can unlock three lines are comments, does appear to run after the above mentioned abnormal

2, look at the source code

 

 

Seems to be no problem, look down

 

 

However, in practice we point into the ArrayList found, in fact, is not what we usually use ArrayList ArrayList. But inside an inner class Arrays. And this internal class does not add, clear, remove method, so exceptions thrown from the fact AbstractList.

 

 

Point into place you will find to throw an exception, the Clear is also called the bottom to remove it will also throw an exception.

Summary :

1, Arrays.asList () do not mess with , the underlying fact or array .

2, if used Arrays.asList (), then , it is best not to use its method of operation set .

3、List list = new ArrayList<>(Arrays.asList("a", "b", "c"))可以在外面这样包一层真正的ArrayList

Guess you like

Origin www.cnblogs.com/dingpl/p/11326443.html