我将如何在 Java 中迭代堆栈

2022-01-22 00:00:00 stack iterator java

我想知道如何在 Stack 类中使用迭代器.如何为它创建一个迭代器类?

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

推荐答案

只需通过 Iteratorapi/java/util/Vector.html#iterator%28%29" rel="noreferrer">iterator():

Just get the Iterator via iterator():

Stack<YourObject> stack = ...

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

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

或者,如果您只想将它​​们全部打印出来,请使用 enhanced-for 循环:

Or alternatively, if you just want to print them all use the enhanced-for loop:

for(YourObject obj : stack)
{
    System.out.println(obj);
}

相关文章