In the previous article, we have discussed about Java LinkedList addLast() Method with Examples
In this article we are going to see the use of Java LinkedList clear() method along with suitable examples.
Java LinkedList clear() Method with Examples
This java.util.LinkedList.clear()
method removes all the elements from a LinkedList. It does not return any value as it removes all the elements from the LinkedList and makes it completely empty.
Syntax:
LinkedListName.clear()
Where,
LinkedListName
refers to the name of your LinkedList.
Let’s see different examples to understand it more clearly.
Example-1: Java LinkedList clear() Method – Example with String Type LinkedList
Approach:
- Create a new LinkedList of type String.
- Add string elements into the LinkedList using the add() method.
- Display the LinkedList elements.
- Then clear all the elements from the LinkedList using clear() method.
- Print the new LinkedList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a LinkedList of string datatype LinkedList<String> l = new LinkedList<String>(); // Adding some elements to the LinkedList l.add("You"); l.add("are"); l.add("learning"); l.add("from"); l.add("BtechGeeks"); // Prints the LinkedList elements System.out.println("The elements of LinkedList are: "+l); // clearing all the element from the LinkedList l.clear(); // Prints the new LinkedList elements System.out.println("Now elements of LinkedList are: "+l); } }
Output: The elements of LinkedList are: [You, are, learning, from, BtechGeeks] Now elements of LinkedList are: []
Example-2: Java LinkedList clear() Method – Example with Integer Type LinkedList
Approach:
- Create a new LinkedList of type Integer.
- Add integer elements into the LinkedList using the add() method.
- Display the LinkedList elements.
- Then clear all the elements from the LinkedList using clear() method.
- Print the new LinkedList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a LinkedList of Integer datatype LinkedList<Integer> l = new LinkedList<Integer>(); // Adding some elements to the LinkedList l.add(2); l.add(52); l.add(13); l.add(17); l.add(1); // Prints the LinkedList elements System.out.println("The elements of LinkedList are: "+l); // clearing all the element from the LinkedList l.clear(); // Prints the new LinkedList elements System.out.println("Now elements of LinkedList are: "+l); } }
Output: The elements of LinkedList are: [2, 52, 13, 17, 1] Now elements of LinkedList are: []
Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language.
Related Java Programs: