我要为我的一个项目添加通用性。我喜欢泛型,因为这使我的代码更加健壮、自我记录并消除了所有那些丑陋的演员表。
但是,我遇到了一个棘手的案例,并且在尝试为我的一个结构表达“递归”约束时遇到了一些问题。
这基本上是某种“通用”树,带有双链接(到子节点和父节点)。我最大程度地简化了课程以显示问题:
public class GenericTree<
ParentClass extends GenericTree<?, ?>,
ChildClass extends GenericTree<?, ?>>
{
// Attributes
private ArrayList<ChildClass> children = new ArrayList<ChildClass>();
private ParentClass parent = null;
// Methods
public void setParent(ParentClass parent) {
this.parent = parent;
}
public void addChild(ChildClass child) {
child.setParent(this);
this.children.add(child);
}
}
问题在于指令:child.setParent(this)。
Java给出以下错误:
绑定不匹配:ChildClass 类型的方法 setParent(?) 不适用于
参数 (GenericTree)。通配符参数 ? 没有下限,实际上可能比参数 GenericTree 更严格
我想要的是能够表达类似的东西:
public class GenericTree<
ParentClass extends GenericTree<?, ?>,
ChildClass extends GenericTree<[THIS_VERY_CLASS], ?>>
要说子类的父类应该是它自己...
我看过一些关于自边界泛型的文章,但我不知道如何在这种情况下应用它。
任何帮助,将不胜感激。