• Java数据结构教程

验证栈是否为空



java.util包的`Stack`类提供了一个`isEmpty()`方法。此方法验证当前栈是否为空。如果给定的向量为空,则此方法返回`true`,否则返回`false`。

示例

import java.util.Stack;
public class StackIsEmpty {
   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 :"+stack);
      stack.clear();
      System.out.println("Contents of the stack after clearing the elements :"+stack);
      
      if(stack.isEmpty()) {
         System.out.println("Given stack is empty");    	  
      } else {
         System.out.println("Given stack is not empty");  
      }
   }
}

输出

Contents of the stack :[455, 555, 655, 755, 855, 955]
Contents of the stack after clearing the elements :[]
Given stack is empty
广告