Create an object that accepts a shared collection

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; // 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 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).

+4
source share
1 answer

The ArrayVisualizer class must specify both the type of the collection and the type of element. You cannot quantify T<String> , as it is in Java. (Other languages ​​can do this, but not Java.)

So, something like ....

 class ArrayVisualizer<E, T extends IterableCollection<E>> { public void draw(T vector) { ... } } 

(although if I were you, I would try to use the pre-built Iterable or Collection interface, and not my own IterableCollection interface)

+4
source

All Articles