java - Iterable interface implementation -


can tell me if implementation stack right?

   class leveliter<node> implements iterable<node> {         stack<node> s = null;         public leveliter(stack<node> s) {             this.s = s;         }         public iterator<node> iterator(){             iterator<node> = new iterator<node>() {                 private int index = 0;                  @override                 public boolean hasnext(){                         return (index < s.size() && !s.isempty());                 }                  @override                 public integer next(){                     return (integer) (s.pop()).data;                 }                  @override                 public void remove(){                     s.remove();                 }             };             return it;         }     } 

where node node in binary tree -

  class node{     int data;     node left;     node right;     public node(int data){         this.data = data;         this.left = null;         this.right = null;     } } 

and calling in main --

    leveliter<node> l = new leveliter<node>(s);     for(int n:l){         system.out.println(n);     } 

an iterator shouldn't modify shared data structure. constructor should copy passed stack doesn't pop elements it.

pass reference , pass value tricky subjects master. you're copying reference in code, leveliter's stack object going same whatever stack passed in. means when iterate using leveliter, going empty whatever stack leveliter constructed with. undesirable , reason suggest following:

class leveliter<node> implements iterable<node> {     stack<node> s = null;     public leveliter(stack<node> s) {         this.s = (stack)s.clone();     }     //rest same. } 

the rest of code looks fine me. best way make sure code works test though. create class tests iterator. make sure functioning way expect.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -