简体   繁体   English

Java中的通用通配符

[英]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. 我想要其他一些子类来继承该Node。 This code cannot be compiled with the error on line parent.getChildren().add(this); 不能编译该代码,并且在parent.getChildren().add(this);行上出现错误parent.getChildren().add(this); . Because I declared getChildren() with List<? extends Node<T>> 因为我用List<? extends Node<T>>声明了getChildren() List<? extends Node<T>> List<? extends Node<T>> as return type, and 'this' is type Node<T> . List<? extends Node<T>>为返回类型,而'this'是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. 例如,它可能被键入为SubClassA,但是您要添加SubClassB,并且它无法根据声明的类型知道,这是编译器必须进行的所有操作。 At runtime, while the type of list and child might match, the compiler can't assert. 在运行时,虽然列表和子级的类型可能匹配,但编译器无法断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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