0

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?

1 Answers1

0

I think the following will work (not tested, so not 100% sure):

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.

Community
  • 1
  • 1
Oliver Dain
  • 9,617
  • 3
  • 35
  • 48
  • Thank you! I thought of using generic types, but I forgot that you can set the type when extending. ex: IntegerNode>>> –  May 08 '16 at 00:25