CKTIS / Java
List.clear(): Emptying a list in Java
`List.clear()` removes every element from an existing list. It returns no value, and not every list supports the operation.
Version: Java SE 21
Syntax
void clear()
list.clear();List.clear() is an instance method of java.util.List. Call it as list.clear(), with no arguments. Its return type is void, so it gives back no value. After a successful call, list.size() returns 0 and list.isEmpty() returns true.
The method changes the existing list rather than creating a new one. If two variables refer to the same list, both see the empty list after the call. Assigning a new list to one variable does not empty the original list.
Clearing is an optional operation. ArrayList supports it, but lists created with List.of(...) or List.copyOf(...) throw UnsupportedOperationException, even if they are already empty. To clear a copy without changing the source, first create new ArrayList<>(list) and call clear() on the copy.
Examples
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> items = new ArrayList<>(List.of("A", "B"));
List<String> sameList = items;
System.out.println(items.size());
items.clear();
System.out.println(items.size());
System.out.println(sameList.isEmpty());
}
}Result
2 0 true
`items` and `sameList` refer to the same `ArrayList`. The output shows size `2` before the call, size `0` afterward, and `true` for `sameList.isEmpty()`.
Related lessons
- Java · Lesson 54 · Basic · Version: 2