Empty a linked list in Java
The Java LinkedList class comes with the clear() method that you can use to empty a linked list instance.
For example, suppose you initialize a LinkedList with Integer values as shown below:
LinkedList myList =
new LinkedList(Arrays.asList(1, 2, 3));
You can empty the myList variable by calling the clear() method like this:
System.out.println(myList);
myList.clear();
System.out.println(myList);
The output of the println() call will be as follows:
[1, 2, 3]
[]
As you can see, the clear() method empties the myList instance, removing all values stored in the variable.
Alternatively, you can also create an empty LinkedList instance during initialization as follows:
LinkedList emptyList = new LinkedList();
You can then add values to the emptyList variable above by calling the add() method:
emptyList.add(1);
emptyList.add(2);
emptyList.add(3);
System.out.println(emptyList); // [1, 2, 3]
Now you’ve learned how to empty a LinkedList variable in Java. Good work! 👍
More Java tutorials
See allJava
How to fix Index 0 out of bounds for length 0 Java exception
Apr 28, 2023
Java
How to get the length of a 2D array in Java
Dec 19, 2022
Java
How to serialize and deserialize a binary tree in Java
Apr 6, 2022
Java
How to create a singleton class in Java
Apr 5, 2022
Java
Java abstract class - with code examples
Apr 4, 2022