Arrays.asList()返回的是一固定長度的List,不支援add() remove() clear()等操作

wangdai發表於2014-11-10

今天又跳一坑, sample code:

List<Integer> list = Arrays.asList(1, 2, 3);
list.clear(); // throws java.lang.UnsupportedOperationException

Arrays.asList()返回的是一個固定長度的List,不支援add() remove() clear()等操作

/**
 * 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 a the array by which the list will be backed
 * @return a list view of the specified array
 */
@SafeVarargs
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

注意上面那個ArrayList是Arrays的內部類,同樣extends了AbstractList但沒有實現add()那些方法,所以就蛋疼了

相關文章