Java Generics Interface with List

Wildcards

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?

public class TreeNode<T> {
private T data;
private List<TreeNode<T>> children;
public T getData() {
return this.data;
}
public List<TreeNode<T>> getChildren() {
return this.children;
}
}
public class DoubleLinkedTreeNode<T> {
private T data;
private List<TreeNode<T>> children;
private DoubleLinkedTreeNode<T> parent;
public T getData() {
return this.data;
}
public List<DoubleLinkedTreeNode<T>> getChildren() {
return this.children;
}
}
view raw tree-node.java hosted with ❤ by GitHub

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:

public interface TreeNodeInterface<T> {
T getData();
List<? extends TreeNodeInterface<T>> getChildren();
}

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.

References


  1. Java Generics ↩︎