How would I iterate a stack in Java [closed]

2020-02-26 06:10发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

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

回答1:

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);
}


回答2:

You could do:

for (Iterator<MyObject> iterator = stack.iterator(); iterator.hasNext();) {
   MyObject myObject = iterator.next();
   myObject.doStuff();
}


回答3:

Stack<Object> myStack; // obtain your Stack object

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


回答4:

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
     }
   }
}


回答5:

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.