I am learning Java generics and I am trying to adapt some code I developed as an exercise.
In particular, I developed an ArrayVisualizer class that uses Sedgewick’s StdDraw library to visualize and animate the behaviour of a dynamic array. I have my own dynamic array class which supports generics, and I am trying to extend the usage of ArrayVisualizer to anything that is akin to this array.
In short, my question is: how can you deal with generic types containing other generic types?
Here is my thought process:
- I started by making this Interface:
public interface IterableCollection<Item> {
void add(Item i);
Item get(int index) throws IndexOutOfBoundsException; // These can be slow for LinkedList implementations
void set(int index, Item value) throws IndexOutOfBoundsException;
int capacity();
int size(); // Capacity and size can be the same for LinkedList implementations
}
- Then, I would like my
ArrayVisualizerclass to take as parameters any class that implements this Interface. After some googling, I found that you can’t write
public class ArrayVisualizer<T implements IterableCollection<?> >
but you have to use extends.
However, even if I write that I can’t use the T class inside my functions.
For example, I have a compiler error if I try to generalize this function:
public static void draw(T<String> vector) throws Exception
It is like I have to specify that T is also generic, but I can’t find a way to declare it. I have tried the following, and none works:
public class ArrayVisualizer<T<?> implements IterableCollection<?> >
public class ArrayVisualizer<T<S> implements IterableCollection<S> >
RESOURCES: I have uploaded the working non-generic version of my code as a reference.
-
ArrayVisualizer.java (this takes some spaced strings as input)
-
InteractiveArrayVisualizer.java (this one doesn’t allow to choose the values of the cells but you can fill them by clicking on the next empty spot and you can empty them by clicking on the last open cell. This is meant to use a debug helper for the resize problem of the dynamic array).
Your
ArrayVisualizerclass must specify both the collection type, and the element type. You cannot quantify overT<String>like that in Java. (Other languages can do it, but not Java.)So, something like….
(although if I were you, I would try to use the pre-built
IterableorCollectioninterface rather than my ownIterableCollectioninterface…)