我正在查看http://docs.oracle.com/javase/tutorial/collections/custom-implementations/index.html教程,我尝试做同样的事情:
class MyArrayList<T> extends AbstractList<T> {
private final T[] a;
MyArrayList(T[] array) {
a = array;
}
@Override
public T get(int index) {
return a[index];
}
@Override
public T set(int index, T element) {
T oldValue = a[index];
a[index] = element;
return oldValue;
}
@Override
public int size() {
return a.length;
}
@Override
public Object[] toArray() {
return (Object[]) a.clone();
}
public static void main(String[] args) {
String[] arr = {"one", "two", "three"};
MyArrayList<String> list = new MyArrayList<String>(arr);
list.get(1);
list.add(1, "seven");
System.out.println(list);
}
}
尝试插入元素时出现异常:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
为什么会这样,我该如何解决?