Gandalf StormCrow Gandalf StormCrow - 3 months ago 28
Java Question

Implementing abstract list

I was looking at the tutorial and I tried to do the same :

class MyArrayList<T> extends AbstractList<T> {

private final T[] a;

MyArrayList(T[] array) {
a = array;

public T get(int index) {
return a[index];

public T set(int index, T element) {
T oldValue = a[index];
a[index] = element;
return oldValue;

public int size() {
return a.length;

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.add(1, "seven");

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?


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.