📜  Java中的 Stack empty() 方法

📅  最后修改于: 2022-05-13 01:55:10.075000             🧑  作者: Mango

Java中的 Stack empty() 方法

Java中的Java .util.Stack.empty() 方法用于检查堆栈是否为空。该方法是布尔类型,如果堆栈为空,则返回 true,否则返回 false。

句法:

STACK.empty()

参数:该方法不带任何参数。

返回值:如果堆栈为空,则该方法返回布尔值 true,否则返回 false。

下面的程序说明了Java.util.Stack.empty() 方法的工作:
方案一:

// Java code to demonstrate empty() method
import java.util.*;
  
public class Stack_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Stack
        Stack STACK = new Stack();
  
        // Stacking strings
        STACK.push("Geeks");
        STACK.push("4");
        STACK.push("Geeks");
        STACK.push("Welcomes");
        STACK.push("You");
  
        // Displaying the Stack
        System.out.println("The stack is: " + STACK);
  
        // Checking for the emptiness of stack
        System.out.println("Is the stack empty? " + 
                                      STACK.empty());
  
        // Popping out all the elements
        STACK.pop();
        STACK.pop();
        STACK.pop();
        STACK.pop();
        STACK.pop();
  
        // Checking for the emptiness of stack
        System.out.println("Is the stack empty? " + 
                                     STACK.empty());
    }
}
输出:
The stack is: [Geeks, 4, Geeks, Welcomes, You]
Is the stack empty? false
Is the stack empty? true

方案二:

// Java code to demonstrate empty() method
import java.util.*;
  
public class Stack_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Stack
        Stack STACK = new Stack();
  
        // Stacking int values
        STACK.push(8);
        STACK.push(5);
        STACK.push(9);
        STACK.push(2);
        STACK.push(4);
  
        // Displaying the Stack
        System.out.println("The stack is: " + STACK);
  
        // Checking for the emptiness of stack
        System.out.println("Is the stack empty? " + 
                                      STACK.empty());
    }
}
输出:
The stack is: [8, 5, 9, 2, 4]
Is the stack empty? false