Search code examples
javadata-structurestreeiteratorinorder

Implementing my own tree Iterator in Java


I as trying to implement the Iterator interface for tree traversal. I am getting the following error."Incompatible types at for(Integer node : tr )" and "treeIterator.java uses unchecked or unsafe operations." I am unable to fix this error. Can someone point out the problem.

//class to implement the Iterator interace.
class InorderItr implements Iterator {



    public InorderItr(Node root) {
       st = new Stack<Node>();
       this.root = root;
    }

    @Override
    public boolean hasNext() {
        //has Next
    }

    @Override
    public Integer next(){
          //next node
    }

    @Override 
    public void remove(){
        throw new java.lang.UnsupportedOperationException("Remove not supported.");
    }
}

//This class just makes sure that we use the foreach loop.
class InorderTreeIterator implements Iterable {

    Node root = null;

    public InorderTreeIterator(Node root){
        this.root = root;
    }

    @Override
    public Iterator<Integer> iterator(){
        try{
            return new InorderItr(this.root);
        } catch(UnsupportedOperationException e){
            System.out.println(e.getMessage());
            return null;
        }
    }
}


class treeIterator {

    public static void main(String arg[]){
        treeIterator obj = new treeIterator();
        //create tree.
        InorderTreeIterator tr = new InorderTreeIterator(obj.root);
        for(Integer node : tr ){
            System.out.println(node);
        }
    }
}

PS: This is my first try at implementing iterator interface. If there are any standard practices that I am not following please point out.

Thank You


Solution

  • Iterable is a generic interface. That means, unless you give it a type parameter, it will be a raw type, and the underlying data will be treated as Object.

    Change this:

    class InorderItr implements Iterator
    class InorderTreeIterator implements Iterable
    

    to the following:

    class InorderItr implements Iterator<Integer>
    class InorderTreeIterator implements Iterable<Integer>
    

    This way, it is no longer a raw type (and that get rids of the warnings of unchecked and unsafe operations the compiler gives you currently), and it tells the compiler that the Iterator will have its underlying data type be Integer (since the type parameter in the Iterator interface is its underlying data type), so the type matches.