在 Java 中清除 LinkedList

可以使用 java.util 方法在 Java 中清除 LinkedList。. 此方法删除 LinkedList 中的所有元素。该方法不需要参数,也不返回任何值。LinkedList.clear()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。LinkedList 在使用清除 LinkedList 的方法之前和之后显示。演示这一点的代码片段如下LinkedList.add()theLinkedList.clear()

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);