java - Implementing an iterator for a stack -
i defined interface stringstack
public interface stringstack{ //add value stack public void push(string value); //fetch top-most element of stack. element removed public string pop(); //fetch top-most element of stack. element not removed public string peek(); } further defined class simplestack uses arraylist manage stack
public class simplestack implements stringstack{ private arraylist<string> list = new arraylist<string>(); public void push(string value){ list.add(value); } public string pop(){ if(!list.isempty()){ return list.remove(list.size() - 1); }else{ return null; } } public string peek(){ if(!list.isempty()){ return list.get(list.size() - 1); }else{ return null; } } now want define iterator stack class don't want use built-in arraylist iterator. came implementing inner class , extending simplestack iterable interface.
so have now:
public class simplestack implements stringstack, iterable<string> ... public iterator<string> iterator(){ return new stackenum(); } class stackenum implements iterator<string>{ int pos = list.size(); public boolean hasnext(){ return pos != 0; } public string next(){ if(pos != 0){ string str = list.get(pos); pos--; }else{ throw new nosuchelementexception(); } } public void remove(){ throw new unsupportedoperationexception(); } } i absolutely not sure how perform iteration inside iterator. since stack represented array list used list.size() top-element.
am right implementation of iterator, next method?
i don't know if iterator stack idea, typical behavior of stack not conform iterator-protocol, you'd have pop element reveal next one. suggest add public method getlist() returns list-representation of stack. list implement iterator interface. return copy of arraylist that:
public list<string> returnlist() { return new arraylist<string>(list); // return copy of arraylist }
Comments
Post a Comment