Hi,
What is the interest of generic types outside
the field of collection types ?
All the examples I found are based
on collection types (thanks to generics
, we avoid an explicit cast when we get an element
from a collection ... ok, that's fine.
But are there any other interesting uses of
generic types ?
I happen to think the way generics are used in the Emum<E extends
Enum<E>> is quite interesting. I've used that idiom myself in several
data structures where I want to swap out some internal class.
For instance, a generic Tree data structure should have the notion of
Nodes, but we want the freedom to implement those Node classes in
different, efficient ways depending on the Tree type. Heaps are tree,
but can be efficiently implement on top of an array. A Red-Black Tree
needs Nodes with an extra "red" boolean flag, etc....
One can implement a generic data type like this:
public interface Tree<V, N extends Node<V, N>> {}
public interface Node<T, Q extends Node<T, Q>> {}
public interface BinaryTree<K extends Comparable<K>, V, N extends
BinaryTreeNode<K,V,N>> extends Tree<E, N>
public interface BinaryTreeNode<S extends Comparable<S>, T, Q extends
BinaryTreeNode<S, T, Q>> extends Node<T, Q>
Now, a concrete implementation of a Red-Black Tree class might look
like this
class RBTree extends BinaryTree<Integer, String, RBNode> {}
class RBNode extends BinaryTreeNode<Integer, String, RBNode> {}
All the complicated-looking generic declarations just make sure that
when I glue a TreeNode class onto a Tree class the Key and Value types
all match up. This lets me have a very loose coupling of the Tree and
Node classes, but still enforce type-safety.
-Lucas
The construct Foo<T extends Foo<T>> allows the class to use T as a
kind of self-referential type, e.g. Tree and