data structures - Implementing my own tree Iterator in Java -
i trying implement iterator interface tree traversal. getting following error."incompatible types @ for(integer node : tr )" , "treeiterator.java uses unchecked or unsafe operations." unable fix error. can point out problem.
//class implement 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 makes sure use 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: first try @ implementing iterator interface. if there standard practices not following please point out.
thank
iterable
generic interface. means, unless give type parameter, raw type, , underlying data treated object
.
change this:
class inorderitr implements iterator class inordertreeiterator implements iterable
to following:
class inorderitr implements iterator<integer> class inordertreeiterator implements iterable<integer>
this way, no longer raw type (and rids of warnings of unchecked , unsafe operations compiler gives currently), , tells compiler iterator
have underlying data type integer
(since type parameter in iterator
interface underlying data type), type matches.
Comments
Post a Comment