DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Aldora
Aldora

Posted on

Java Generics Interface with List

Wildcards

How to write a generic interface with List of implemented classes of the interface?

I encounter this problem when I write a tree node interface, here are 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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

You can view my explanation here

Top comments (0)

Build Anything...


Use any Linode offering to create something for the DEV x Linode Hackathon 2022. A variety of prizes are up for grabs, inculding $1,000 USD. πŸ‘€

β†’ Join the Hackathon <-