Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I iterate a stack in Java [closed]

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

like image 985
Ervin Lucci Avatar asked Oct 18 '12 14:10

Ervin Lucci


People also ask

Can we iterate stack in Java?

The Java. util. Stack. iterator() method is used to return an iterator of the same elements as that of the Stack.

How do you iterate a stack?

Iterating over a StackIterate over a Stack using Java 8 forEach(). Iterate over a Stack using iterator(). Iterate over a Stack using iterator() and Java 8 forEachRemaining() method. Iterate over a Stack from Top to Bottom using listIterator().

Does stack have an iterator?

Stack does not have iterators, by definition of stack. If you need stack with iterators, you'll need to implement it yourself on top of other container (std::list, std::vector, etc).

Can you use a For Each loop on a stack?

In Scala Stack class , the foreach() method is utilized to apply a given function to all the elements of the stack.


1 Answers

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);
}
like image 156
Baz Avatar answered Nov 06 '22 01:11

Baz