I am reading the Oracle documentation about creating custom implementations of the Collections interface. The example they give (copied below) instantiates a custom implementation of an ArrayList by passing an Array into the constructor. My understanding is that an ArrayList starts empty and can then expand to arbitrary size by adding elements. By contrast, my recollection is that the size of an Array must be specified at the time the Array is instantiated and that the size of the Array cannot change afterwards.
So why does the example from Oracle below pass an Array into the custom ArrayList implementation? How would you modify the below to be able to accommodate arbitrary expansion and contraction in size after a new MyArrayList has been instantiated?
public static <T> List<T> asList(T[] a) {
return new MyArrayList<T>(a);
}
private static 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;
}
}