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. With an extended class, the inherited iterator method still returns the Node iterator, which means I have to cast every time. 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?