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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With