问题:
直接原因:
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方法, 从而报错。