打印栈的元素
您可以直接使用 println() 方法打印栈的内容。
System.out.println(stack)
Stack 类也提供 iterator() 方法。此方法返回当前 Stack 的迭代器。使用此方法,您可以逐个打印栈的内容。
示例
import java.util.Iterator;
import java.util.Stack;
public class PrintingElements {
public static void main(String args[]) {
Stack stack = new Stack();
stack.push(455);
stack.push(555);
stack.push(655);
stack.push(755);
stack.push(855);
stack.push(955);
System.out.println("Contents of the stack :");
Iterator it = stack.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
输出
Contents of the stack : 455 555 655 755 855 955
广告