I am wondering how to use the iterator in a Stack class. How do I create a iterator class for it?
The Java. util. Stack. iterator() method is used to return an iterator of the same elements as that of the 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().
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).
In Scala Stack class , the foreach() method is utilized to apply a given function to all the elements of the stack.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With