Java Generics Interface with List


How to write a generic interface with List or Collection of implemented class of the interface?

I encounter to this problem when I write a tree node interface, here is the details of the problem: I need to create an interface for the following two classes, how to write the interface?

Both classes have getData and getChildren method, and they are the methods interface need to define. However, the tricky part is how to represent the TreeNode or DoubleLinkedTreeNode in their interface? The answer is: wildcards, here is the interface:

The reason I use question mark ?, which is the wildcards, is that it refers to unknown types. This is because that a collection of Object is not the supertype of any collection[1]. For example, List<TreeNodeInterface<T>> is not the supertype of List<DoubleLinkedTreeNode<T>>, so with ? extends TreeNodeInterface<T>, I represent all subtypes of TreeNodeInterface<T>. This is called upper-bounded wildcard, where type TreeNodeInterface<T> is the upper bound.


  1. Java Generics ↩︎