21

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

Community
  • 1
  • 1
Ervin Lucci
  • 227
  • 1
  • 2
  • 8

5 Answers5

24

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);
}
Baz
  • 36,440
  • 11
  • 68
  • 94
  • Without iterator - while (!stack.isEmpty()) { ... currentSymbol = stack.pop();...} – Hitesh Sahu May 13 '16 at 04:23
  • 3
    @HiteshSahu After running your code, the `Stack` will be empty as `pop()` removes the top of the stack. – Baz May 13 '16 at 08:17
  • Agree . I was building a compiler and I was using this variation for syntex parsing. – Hitesh Sahu May 14 '16 at 01:39
  • 3
    There's a bug in the stack iterator, and this approach doesn't return LIFO order. http://stackoverflow.com/questions/16992758/is-there-a-bug-in-java-util-stacks-iterator – user3170122 May 18 '17 at 15:30
4

You could do:

for (Iterator<MyObject> iterator = stack.iterator(); iterator.hasNext();) {
   MyObject myObject = iterator.next();
   myObject.doStuff();
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1
Stack<Object> myStack; // obtain your Stack object

Iterator iterator = myStack.iterator();
while (iterator.hasNext()) {
   Object object = iterator.next();
}
1

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
     }
   }
}
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

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.

evanwong
  • 5,054
  • 3
  • 31
  • 44