java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.yxxmg.collection.CollectionTest.test(CollectionTest.java:21)
先分析下Arrays.asList
,java.util.Arrays#asList
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
private final E[] a;
ArrayList(E[] array) {
a = Objects.requireNonNull(array);
}
public boolean add(E e) {
add(size(), e);
return true;
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
由此可以看出asList其实就是就是一个定长数组且不能被修改,类似apache commons-collections
中的Collections.unmodifiableList()
1.使用Guava
的Lists
2.使用Stream.of()
操作
3.使用Arrays.stream()
4.使用new ArrayList<>(Collection<? extends E> c)
https://gitee.com/youxiaxiaomage/java-practices/blob/master/yxxmg-java-helper/src/test/java/com/yxxmg/collection/CollectionTest.java