Java中的Stack clear()方法及示例

Java中的Stack clear()方法及示例

Java.util.Stack.clear() 方法用于从Stack中删除所有元素。使用clear()方法仅清除Stack中的所有元素,不删除Stack。换句话说,我们可以说clear()方法仅用于清空现有的Stack。

语法:

Stack.clear()

参数: 该方法不接受任何参数。

返回值: 该函数不返回任何值。

下面的程序说明了Java.util.Stack.clear()方法。

示例1:

// Java code to illustrate clear()
import java.util.*;
  
public class GFG {
    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);
  
        // Clearing the Stack using clear() method
        stack.clear();
  
        // Displaying the final Stack after clearing;
        System.out.println("The final Stack: " + stack);
    }
}
Stack: [Welcome, To, Geeks, 4, Geeks]
The final Stack: []

示例2:

// Java code to illustrate clear()
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<Integer> stack = new Stack<Integer>();
  
        // Use add() method to add elements into the Queue
        stack.add(10);
        stack.add(15);
        stack.add(30);
        stack.add(20);
        stack.add(5);
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // Clearing the Stack using clear() method
        stack.clear();
  
        // Displaying the final Stack after clearing;
        System.out.println("The final Stack: " + stack);
    }
}
Stack: [10, 15, 30, 20, 5]
The final Stack: []

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程