我一直在尋找在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)
這是爲什麼,我如何解決它?