Generic Implementation
- Implement the generic IndexedList ADT with a concrete Java class.
We must also update the implementation of the ArrayIndexedList since the IndexedList ADT uses generics.
-
Update the class declaration, parameters, and return types.
public class ArrayIndexedList<T> implements IndexedList<T> { @Override public void put(int index, T value) { // stub } @Override public T get(int index) { return null; // stub } @Override public int length() { return 0; // stub } }Notice the
<T>follows class name and interface name. -
Define the fields with a generic type. Here we need a generic array.
private T[] data; -
Initialize the fields in a constructor (instantiate when needed). We will leave this for the next lesson!
-
Implement the methods.
Here are implementations for
getandlength@Override public T get(int index) { return data[index]; } @Override public int length() { return data.length; }Exercise Implement
put.Solution
@Override public void put(int index, T value) { data[index] = value; }Notice the implementation of
get,lengthandputare identical to before using generics. This is the beauty of it: using generics in most cases requires very little change to your code.