检查Java中堆栈是否为空
方法java.util.Stack.empty()用于检查堆栈是否为空。此方法不需要任何参数。如果堆栈为空,则返回true;如果堆栈不为空,则返回false。
演示此的程序如下所示-
示例
import java.util.Stack;public class Demo {
public static void main (String args[]) {
Stack stack = new Stack();
stack.push("Amy");
stack.push("John");
stack.push("Mary");
System.out.println("The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
System.out.println("\nThe element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("\nThe stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
}
}
输出结果
The stack elements are: [Amy, John, Mary]The stack is empty? false
The element that was popped is: Mary
The element that was popped is: John
The element that was popped is: Amy
The stack elements are: []
The stack is empty? true
现在让我们了解上面的程序。
已创建堆栈。然后使用Stack.push()方法将元素添加到堆栈中。显示堆栈,然后使用Stack.empty()方法检查堆栈是否为空。演示这的代码片段如下-
Stack stack = new Stack();stack.push("Amy");
stack.push("John");
stack.push("Mary");
System.out.println("The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
Stack.pop()方法用于弹出三个堆栈元素。显示堆栈,然后使用Stack.empty()方法检查堆栈是否为空。演示这的代码片段如下-
System.out.println("\nThe element that was popped is: " + stack.pop());System.out.println("The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("\nThe stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
以上是 检查Java中堆栈是否为空 的全部内容, 来源链接: utcz.com/z/316067.html