当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stack isEmpty()用法及代码示例


Java中的Java.util.Stack.isEmpty()方法用于检查和验证Stack是否为空。如果堆栈为空,则返回True,否则返回False。

用法:

Stack.isEmpty()

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


返回值:如果Stackis为空,则此函数返回True,否则返回False。

以下示例程序旨在说明Java.util.Stack.isEmpty()方法:

示例1:

// Java code to illustrate isEmpty() 
import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Stack 
        Stack<String> stack = new Stack<String>(); 
  
        // Use add() method to add elements into the Stack 
        stack.add("Welcome"); 
        stack.add("To"); 
        stack.add("Geeks"); 
        stack.add("4"); 
        stack.add("Geeks"); 
  
        // Displaying the Stack 
        System.out.println("Stack:  " + stack); 
  
        // Verifying if the Stack is empty or not 
        System.out.println("Is the Stack empty? "
                           + stack.isEmpty()); 
  
        // Clearing the Stack 
        stack.clear(); 
  
        // Displaying the Stack 
        System.out.println("Stack after clear(): "
                           + stack); 
  
        // Verifying if the Stack is empty or not 
        System.out.println("Is the Stack empty? "
                           + stack.isEmpty()); 
    } 
}
输出:
Stack:  [Welcome, To, Geeks, 4, Geeks]
Is the Stack empty? false
Stack after clear(): []
Is the Stack empty? true

示例2:

// Java code to illustrate isEmpty() 
import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Stack 
        Stack<Integer> stack = new Stack<Integer>(); 
  
        // Displaying the Stack 
        System.out.println("Stack:  " + stack); 
  
        // Verifying if the Stack is empty or not 
        System.out.println("Is the Stack empty? "
                           + stack.isEmpty()); 
    } 
}
输出:
Stack:  []
Is the Stack empty? true


相关用法


注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack isEmpty() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。