Java.util.Stack.clear()方法用於從堆棧中刪除所有元素。使用clear()方法僅清除堆棧中的所有元素,而不刪除堆棧。換句話說,可以說clear()方法僅用於清空現有堆棧。
用法:
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: []
相關用法
- Java Map clear()用法及代碼示例
- Java LinkedBlockingQueue clear()用法及代碼示例
- Java DelayQueue clear()用法及代碼示例
- Java Hashtable clear()用法及代碼示例
- Java HashSet clear()用法及代碼示例
- Java AbstractSequentialList clear()用法及代碼示例
- Java PriorityBlockingQueue clear()用法及代碼示例
- Java HashMap clear()用法及代碼示例
- Java ArrayBlockingQueue clear()用法及代碼示例
- Java LinkedList clear()用法及代碼示例
- Java CopyOnWriteArraySet clear()用法及代碼示例
- Java ConcurrentLinkedDeque clear()用法及代碼示例
- Java NavigableMap clear()用法及代碼示例
- Java LinkedHashMap clear()用法及代碼示例
- Java ArrayDeque clear()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack clear() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。