Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

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?

Upvotes: 2

Views: 7251

Answers (5)

Hao Deng
Hao Deng

Reputation: 643

First of all, do you really need to implement an abstract list? In most of the cases, java List is enough for you.

Annoying part of implementing an abstract class is you have to implement every methods which throws UnsupportedOperationException.

Upvotes: 0

amaidment
amaidment

Reputation: 7298

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.

Upvotes: 9

peshkira
peshkira

Reputation: 6239

From the java documentation of Abstract List:

"To implement a modifiable list, the programmer must additionally override the set(int, E) method (which otherwise throws an UnsupportedOperationException). If the list is variable-size the programmer must additionally override the add(int, E) and remove(int) methods."

You have to override the add method :)

Upvotes: 1

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

add is optional on list. AbstractList implements it to throw and exception. If you want it to do something else, then you can simply override it.

Upvotes: 0

npe
npe

Reputation: 15719

You need to implement add method if you want a mutable list.

Upvotes: 0

Related Questions