Arrays.asList()返回只讀的List

List<Integer> list = Arrays.asList(1, 2, 3);

list.clear(); // throws java.lang.UnsupportedOperationException

對Arrays.asList()轉化的List是一個固定長度的List,不支持add() remove() clear()等操作


Arrays.asList()返回的是一個ArrayList對象

@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
   return new ArrayList<>(a);
}
而這個類繼承自AbstractList類

AbstractList中而這個類中實現的所有對list的數據編輯操作都會拋出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 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();
   }

所以Arrays.asList()返回的list是隻讀的並不能對list的數據進行相關修改!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章