我正在写一个通用类:通用通配符在Java中
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;
}
}
我想其中此类子节点的一些其他类。此代码无法通过parent.getChildren().add(this);
上的错误进行编译。因为我用List<? extends Node<T>>
作为返回类型声明了getChildren(),而'this'是Node<T>
。
有没有办法解决这个问题?
http://stackoverflow.com/questions/1292109/generics-get-andput-rule –