A Generic DynamicArray
Let’s turn our int-only DynamicArray into one that works for any element type.
The change starts in the class header. We declare a type parameter in angle brackets right after the class name:
public class DynamicArray<T> {
...
}
The T is a stand-in for “whatever element type the caller chooses.” Inside the class we can now use T as if it were a real type, even though we will not know what it actually is until the caller creates a DynamicArray. T is just a conventional name, short for “type”. You could call it anything.
Not every int becomes T
Now we go through the class and replace the element type with T. Be careful here. Our class uses int for two different purposes:
- as the type of the elements we store, and
- as the type of indices and counts (
size, theindexparameters).
Only the first kind becomes T. Indices and counts are still int, no matter what we are storing.
So the fields become:
private T[] arr; // elements are now T...
private int size; // ...but size is still a count, an int
And the methods change only where an element is involved:
public void add(T value) { // was int value
if (size == arr.length) {
grow();
}
arr[size] = value;
size++;
}
public T get(int index) { // returns an element, so T; index stays int
return arr[index];
}
public void set(int index, T value) { // index stays int, value becomes T
arr[index] = value;
}
The rest, indexOf, contains, and remove, change the same way: their value parameters become T, while their indices stay int. The growing, shifting, and counting logic is untouched, because none of it depends on what the elements are.
One line that does not compile
The problem is in the constructor:
public DynamicArray() {
arr = new T[10]; // does not compile!
size = 0;
}
Java does not let us create an array of a type parameter. Every other change in the class was a find-and-replace, but this one is not. We have to fix this line before our generic DynamicArray can run.