ArrayList Arrays.asList created not java.util.ArrayList

The project has encountered to be generated ArrayList Arrays.asList add an UnsupportedOperationException abnormal operating Times. This is because he is not ArrayList ArrayList.
Here Insert Picture Description
Arrays ArrayList generated here is private static inner classes.
Here Insert Picture Description
And java.util.ArrayList very similar, are inherited from AbstractList. But only rewrite the toArray, get, set, indexOf, contains, forEach and other methods, and does not override add, add in the parent class
Here Insert Picture Description
and that is why its reasons add will throw the exception.
Besides a small detail, there is a comment on this asList method @SafeVarargs of the notes is JDK1.7 introduced, the main purpose is to handle variable-length parameters generics, tells the compiler, ubiquitous variable-length parameters type is type-safe. The variable length parameter is stored using an array, and the array can not be generic and well mixed.
There is also a similar method to quickly create List Collections.singletonList is the same, get a static inner classes SingletonList Collections of.
Is one such example List List HttpMessageConverter allow caching supportedMediaTypes can only query traversal ordering, do not allow add.
Here Insert Picture Description
So there needs to expand MediaType when the need to redefine a ArrayList, the original addAll inside.
Here Insert Picture Description

Published 26 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_36142042/article/details/104861911