列印棧的元素
您可以直接使用 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
廣告