Arrays.asList的坑

問題:
在這裏插入圖片描述
直接原因:

   public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

舉個例子:下面2種方式有什麼區別?
第一種
在這裏插入圖片描述

第二種
在這裏插入圖片描述
第二種運行時會崩潰!!!

在這裏插入圖片描述

/**
 * Returns a fixed-size list backed by the specified array.  (Changes to
 * the returned list "write through" to the array.)  This method acts
 * as bridge between array-based and collection-based APIs, in
 * combination with {@link Collection#toArray}.  The returned list is
 * serializable and implements {@link RandomAccess}.
 *
 * <p>This method also provides a convenient way to create a fixed-size
 * list initialized to contain several elements:
 * <pre>
 *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
 * </pre>
 *
 * @param <T> the class of the objects in the array
 * @param a the array by which the list will be backed
 * @return a list view of the specified array
 */

Arrays.asList返回的是內部類ArrayList對象且是不可變的(注意 private final E[] a), 而不是ArrayList.java, 即真假李逵。
這個內部類ArrayList沒覆蓋基類AbstractList的add方式, 所以在執行add方法時找的是基類的add方法, 從而報錯。

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