當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stack empty()用法及代碼示例


Java中的java.util.Stack.empty()方法用於檢查堆棧是否為空。該方法為布爾型,如果堆棧為空,則返回true,否則返回false。

用法:

STACK.empty()

參數:該方法不帶任何參數。


返回值:如果堆棧為空,則該方法返回boolean true,否則返回false。

以下程序說明了java.util.Stack.empty()方法的用法:
示例1:

// Java code to demonstrate empty() method 
import java.util.*; 
  
public class Stack_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty Stack 
        Stack<String> STACK = new Stack<String>(); 
  
        // 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

示例2:

// Java code to demonstrate empty() method 
import java.util.*; 
  
public class Stack_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty Stack 
        Stack<Integer> STACK = new Stack<Integer>(); 
  
        // 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


相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Stack empty() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。