How would I iterate a stack in Java [closed]

2020-02-26 05:15发布

I am wondering how to use the iterator in a Stack class. How do I create a iterator class for it?

5条回答
爷、活的狠高调
2楼-- · 2020-02-26 05:52

You could do:

for (Iterator<MyObject> iterator = stack.iterator(); iterator.hasNext();) {
   MyObject myObject = iterator.next();
   myObject.doStuff();
}
查看更多
Evening l夕情丶
3楼-- · 2020-02-26 06:07

Just get the Iterator via iterator():

Stack<YourObject> stack = ...

Iterator<YourObject> iter = stack.iterator();

while (iter.hasNext()){
    System.out.println(iter.next());
}

Or alternatively, if you just want to print them all use the enhanced-for loop:

for(YourObject obj : stack)
{
    System.out.println(obj);
}
查看更多
何必那么认真
4楼-- · 2020-02-26 06:09

I am working on something that is implementing a stack using queues

Does that mean you are not using the Java Stack implementation? http://docs.oracle.com/javase/6/docs/api/java/util/Stack.html It is base on Vector not queues.

If you are using the Java Stack implementation, you can use iterator like other answers. Otherwise, if that's a custom Stack, you have to implement the Iterable interface. And then you can do something like other answers.

查看更多
Anthone
5楼-- · 2020-02-26 06:13
Stack<Object> myStack; // obtain your Stack object

Iterator iterator = myStack.iterator();
while (iterator.hasNext()) {
   Object object = iterator.next();
}
查看更多
聊天终结者
6楼-- · 2020-02-26 06:13

Sounds like you implemented a custom stack class. Your "something" should implement the Iterable interface and provide an implementation of Iterator.

public class MySomethingThatIsAStack<T> implements Iterable<T> {

   @Override
   public Iterator<T> iterator() {
     return new Iterator<T>() {
         // your implementation of the iterator, namely the
         // methods hasNext, next and remove
     }
   }
}
查看更多
登录 后发表回答