We can use clear() method to remove all elements from a linked list in java.
Syntax:
linkedList.clear();
Example:
package com.w3schools;
import java.util.LinkedList;
public class Test {
public static void main(String args[]){
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Jai");
linkedList.add("Mahesh");
linkedList.add("Naren");
linkedList.add("Vivek");
linkedList.add("Vishal");
linkedList.add("Hemant");
System.out.println("Actual LinkedList:"+linkedList);
linkedList.clear();
System.out.println("LinkedList after clear :"+linkedList);
}
} |
package com.w3schools;
import java.util.LinkedList;
public class Test {
public static void main(String args[]){
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Jai");
linkedList.add("Mahesh");
linkedList.add("Naren");
linkedList.add("Vivek");
linkedList.add("Vishal");
linkedList.add("Hemant");
System.out.println("Actual LinkedList:"+linkedList);
linkedList.clear();
System.out.println("LinkedList after clear :"+linkedList);
}
}
Output
Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
LinkedList after clear :[] |
Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
LinkedList after clear :[]