How to Remove All Elements of LinkedList in Java


This example will use clear or removeAll method to remove all elements of LinkedList in Java.

Source Code

package com.beginner.examples;

import java.util.LinkedList;

public class RemoveAllElementsLinkedList {

	public static void main(String[] args) {
		
		//create LinkedList.
		LinkedList linkedList = new LinkedList();
		
		linkedList.add("A");
		linkedList.add("B");
		linkedList.add("C");
		linkedList.add("D");
		
		System.out.println("Before remove all elements, linkedList is  : " + linkedList);
		/*
		 * To remove all elements of Java LinkedList, use
                 * clear() method.
		 */
		linkedList.clear();
		System.out.println("After remove all elements, linkedList is  : " + linkedList);

	}

}

Output:

Before remove all elements, linkedList is  : [A, B, C, D]
After remove all elements, linkedList is  : []

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments