問題:
直接原因:
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<String> 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方法, 從而報錯。