清除 Java 中的 LinkedList


可以使用 java.util.LinkedList.clear() 方法清除 Java 中的 LinkedList。此方法會刪除 LinkedList 中的所有元素。LinkedList.clear() 方法不要求具有任何引數,並且不會返回值。

一個對此進行演示的程式如下所示。

示例

 線上演示

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Orange");
      l.add("Apple");
      l.add("Peach");
      l.add("Guava");
      System.out.println("LinkedList before using the LinkedList.clear() method: " + l);
      l.clear();
      System.out.println("LinkedList after using the LinkedList.clear() method: " + l);
   }
}

上述程式的輸出如下所示

LinkedList before using the LinkedList.clear() method: [Orange, Apple, Peach, Guava]
LinkedList after using the LinkedList.clear() method: []

現在讓我們瞭解一下上述程式。

建立 LinkedList l,然後使用 LinkedList.add() 將元素新增到此 LinkedList 中。在使用 LinkedList.clear() 方法(該方法會清除 LinkedList)之前和之後顯示 LinkedList。展示此過程的程式碼片段如下所示

LinkedList<String> l = new LinkedList<String>();
l.add("Orange");
l.add("Apple");
l.add("Peach");
l.add("Guava");
System.out.println("LinkedList before using the LinkedList.clear() method: " + l);
l.clear();
System.out.println("LinkedList after using the LinkedList.clear() method: " + l);

更新日期:2019 年 7 月 30 日

1 千次以上的瀏覽量

開啟您的 職業

透過完成課程進行認證

開始
廣告
© . All rights reserved.