How do I iterate over a stack in Java

I want to know how to use iterators in the stack class How do I create an iterator class for it?

Solution

Just get the iterator through iterator():

Stack<YourObject> stack = ...

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

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

Or, if you just want to print, use enhanced for loop:

for(YourObject obj : stack)
{
    System.out.println(obj);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>