I am learning Java generics and I am trying to adapt some code that I developed as an exercise.
In particular, I developed the ArrayVisualizer class, which uses Sedgewick StdDraw to visualize and animate the behavior of a dynamic array. I have my own class of dynamic arrays that supports generics, and I'm trying to extend the use of ArrayVisualizer to everything that is akin to this array.
In short, my question is: how can you handle generic types containing other generic types?
Here is my thought process:
- I started by creating this interface:
public interface IterableCollection<Item> { void add(Item i); Item get(int index) throws IndexOutOfBoundsException;
- Then I would like my
ArrayVisualizer class ArrayVisualizer accept as parameters any class that implements this interface. After some searches, I found that you cannot write
public class ArrayVisualizer<T implements IterableCollection<?> >
but you have to use extensions.
However, even if I write that I cannot use the class T 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
As if I should point out that T is also generic, but I cannot find a way to declare it. I tried the following and nobody works:
public class ArrayVisualizer<T<?> implements IterableCollection<?> > public class ArrayVisualizer<T<S> implements IterableCollection<S> >
RESOURCES: I downloaded the working non-native version of my code as a link.
DynamicArray.java
ArrayVisualizer.java (some intermediate lines are used as input)
InteractiveArrayVisualizer.java (this one does not allow you to select cell values, but you can fill them by clicking on the next empty space and you can clear them by clicking on the last opened cell. This is intended to use the debug assistant for the problem of resizing a dynamic array).
source share