Gandalf StormCrow Gandalf StormCrow - 15 days ago 7
Java Question

Implementing abstract list

I was looking at the http://docs.oracle.com/javase/tutorial/collections/custom-implementations/index.html tutorial and I tried to do the same :

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);
}
}


I get an exception while trying to insert the element :

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)


Why is that, how do I fix it?

Answer

You are not overriding the method add().

The javadoc for AbstractList states:

Note that this implementation throws an UnsupportedOperationException unless add(int, Object) is overridden.

The fix is... to override the method. Or not use the add() method so your MyArrayList's size is immutable (but not it's values) - like an array, which is what you're storing your values in.