简体   繁体   中英

Generic wildcard in Java

I'm writing a generic class:

public class Node<T> {
    private Node<T> parent = null;
    private List<? extends Node<T>> children = null;

    public Node<T> getParent() {
        return parent;
    }

    public void setParent(Node<T> parent) {
        if(this.parent != null){
            // Remove current parent's children references
            this.parent.getChildren().remove(this);
        }

        // Add references
        this.parent = parent;
        parent.getChildren().add(this);
    }

    public List<? extends Node<T>> getChildren() {
        return children;
    }
}

I want some other class which subclass this Node. This code cannot be compiled with the error on line parent.getChildren().add(this); . Because I declared getChildren() with List<? extends Node<T>> List<? extends Node<T>> as return type, and 'this' is type Node<T> .

Is there anyway to solve this?

Declare the list as:

List<Node<T>> children

You may still put instances of subclasses in the list.

If you leave it as an unknown type, the compiler can't ensure which class it is typed as. Eg it might be typed as SubClassA, but you're adding SubClassB and it has no way to know based on the declared type , which is all the compiler has to go on. At runtime, while the type of list and child might match, the compiler can't assert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM