今天又跳一坑, 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()那些方法,所以就蛋疼了


wangdai
1k 声望18 粉丝