Press "Enter" to skip to content

LinkedList clear() method with example in java

The clear(E element) method of LinkedList removes all the elements from this list. The linked list becomes empty as a result of this call.

Syntax

void clear()

Parameters

This method doesn't take any parameter.

Return Value

It does not return anything

Program

import java.util.LinkedList;

public class LinkedListClearExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
		oddNumbers.clear();
		System.out.println("Linked List elements after clear(): " + oddNumbers);
	}
}

Output

Linked List elements: [5, 7, 9, 11]
Linked List elements after clear(): []

Be First to Comment

Leave a Reply

Your email address will not be published.