[英]Java Class that iterates its own type when extended
I would like to create a custom tree data structure with nodes only, where I could iterate over them. 我想创建一个仅包含节点的自定义树数据结构,在其中可以遍历它们。 Then, I could later extend this class and have very basic tree
然后,我可以稍后扩展此类,并拥有非常基本的树
class Node{
Node parent;
ArrayList<Node> children;
public static void main(String[]args){
Node root = new Node();
for(Node child : root){
//do something
}
}
public Iterator<Node> iterator(){
// basic tree traversal iterator
}
}
I have gotten this to work, but the issue comes when I try to extend the Node class. 我已经开始工作了,但是当我尝试扩展Node类时,问题就来了。 With an extended class, the inherited iterator method still returns the Node iterator, which means I have to cast every time.
对于扩展类,继承的迭代器方法仍然返回Node迭代器,这意味着我每次都必须进行转换。 Here's a basic example of the issue I run into.
这是我遇到的问题的一个基本示例。 Let's make a tree that holds Integers:
让我们来制作一棵容纳整数的树:
class IntegerNode extends Node{
int value;
public static void main(String[]args){
IntegerNode root = new IntegerNode();
int total = 0;
for(IntegerNode child : root){ /* Compiler error, says that the
iterator returns Iterator<Node> and not Iterator<IntegerNode>*/
total+=child.value;
}
System.out.println(total);
}
}
Is there an easy way to fix this without needing to copy the iterator() method from the Node class into the IntegerNode class? 有没有一种简便的方法可以解决此问题,而无需将iterator()方法从Node类复制到IntegerNode类中?
I think the following will work (not tested, so not 100% sure): 我认为以下方法会起作用(未经测试,因此不能100%确定):
class Node<T extends Node<T>> {
public Iterator<T> iterator(){
// basic tree traversal iterator
}
}
class IntegerNode extends Node<IntegerNode> {
public static void main(String[]args) {
IntegerNode root = new IntegerNode();
int total = 0;
for(IntegerNode child : root){
total += child.value;
}
System.out.println(total);
}
}
This is basically an extension of the quasi-standard inheritable builder pattern . 这基本上是准标准可继承构建器模式的扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.