开发者

Implementing an iterator for a stack

I defined an interface StringStack

public interface StringStack{
    //add a value to the stack
    public void push(String value);
    //fetch top-most element of the stack. element is removed
    public String pop();
    //fetch top-most element of the stack. element is not removed
    public String peek();
}

Further I defined a class SimpleStack that uses an ArrayList to manage the 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);
      开发者_StackOverflow中文版  }else{
                return null;
        }
    }

   public String peek(){
        if(!list.isEmpty()){
                return list.get(list.size() - 1);
        }else{
                return null;
        }
}

Now I want define an iterator for my stack class but I don't want to use the built-in ArrayList iterator. So I came up implementing a inner class and extending my SimpleStack with the Iterable interface.

So I 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 am absolutely not sure how to perform the iteration inside the iterator. Since my stack is represented by an array list I used list.size() as top-element.

Am I right with my implementation of the iterator, especially the next method?


I don't know if an Iterator for a stack is a good idea, as the typical behavior of a stack does not conform to the iterator-protocol, as you'd have to pop an element to reveal the next one. I would suggest to add a public method like getList() which returns a list-representation of the stack. The list then could implement the Iterator interface. You could just return a copy of the ArrayList like that:

public List<String> returnList() {
  return new ArrayList<String>(list); // Return a copy of the ArrayList
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜