asList(T... a)傳回的是一個固定大小的list集合
源碼分析:
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
此時的ArrayList為Arrays裡面自定義的一個私有的内部類
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
其父類AbstractList中事務方法都被禁止了,使用時需要確定傳回的list不會去修改。若需要修改可以修改為
new ArrayList<>(Arrays.asList(T... a));
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
throw new UnsupportedOperationException();
}