In Java, clear() removes every element from the LinkedList. Afterwards size() is 0 and isEmpty() is true.
The list object itself stays alive and can be filled again. The method returns nothing, and it works in time proportional to the number of elements, because each link is cut so that the elements can be garbage collected.
An instance method of java.util.LinkedList (since Java 1.2): call it on a LinkedList object. Add import java.util.LinkedList; at the top of your file. It is declared by List, and LinkedList implements it.
Syntax
Call it with no arguments.
Java
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.clear(); // []
boolean empty = list.isEmpty(); // true
Call
What it does
list.clear()
Removes every element. Returns nothing.
list = new LinkedList<>()
Points the variable at a brand-new empty list instead.
list.isEmpty()
Checks whether the list has no elements.
list.removeAll(c)
Removes only selected elements.
clear() keeps the same list object. Any other variable that points to the list sees it become empty too.
One list for all rounds. The same batch object is used every time.
Cleared at the start. Each round begins with clear(), so values from the previous round never leak in.
Growing batches. Round 1 adds one number, round 2 adds two, and round 3 adds three.
Only the latest values appear. Every printed line shows just the numbers of that round.
Example 3 — See Who Else Sees the Cleared List
Clear a list that has an alias and a separate copy, and compare what each one shows.
Java
import java.util.Arrays;
import java.util.LinkedList;
public class LinkedListClearAlias {
public static void main(String[] args) {
LinkedList<String> original = new LinkedList<>(Arrays.asList("x", "y", "z"));
LinkedList<String> alias = original;
LinkedList<String> copy = new LinkedList<>(original);
original.clear();
System.out.println("original: " + original);
System.out.println("alias: " + alias);
System.out.println("copy: " + copy);
System.out.println("alias is same object: " + (alias == original));
}
}
Output
original: []
alias: []
copy: [x, y, z]
alias is same object: true
How It Works
Three variables.alias points to the very same list object, and copy is a new list with the same elements.
clear empties the shared object. The original list loses all its elements.
The alias sees it too. It is not a separate list, so it also prints as empty.
The copy is safe. It has its own nodes, so x, y and z are still there, and the last line confirms that the alias is the same object.
Frequently Asked Questions
Call list.clear(). It removes all elements and leaves an empty list that can be used again.
clear() empties the existing object, so every variable that points to it sees an empty list. new LinkedList<>() creates a separate list and leaves the old one untouched.
No. Its return type is void.
No. Copy the list first with new LinkedList<>(list) if you may need them later.
Yes. It simply does nothing and throws no exception.