In this guide, you will learn about the List clear() method in Java programming and how to use it with an example.
1. List clear() Method Overview
Definition:
The clear() method of the Java List interface is used to remove all the elements from a list, essentially making it empty.
Syntax:
list.clear()
Parameters:
None.
Key Points:
- The list will be empty after this call returns.
- If the list is immutable, like that returned by List.of(), the clear() method will throw an UnsupportedOperationException.
- It's a fast operation regardless of the list size, as it does not need to return or process the removed elements.
2. List clear() Method Example
import java.util.ArrayList;
import java.util.List;
public class ListClearExample {
public static void main(String[] args) {
// Create a new ArrayList with some elements
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println(fruits); // Outputs: [Apple, Banana, Cherry]
// Use clear() to remove all elements from the list
fruits.clear();
System.out.println(fruits); // Outputs: []
// Trying to clear an immutable list will throw an exception
List<String> immutableFruits = List.of("Apple", "Banana");
// Uncommenting the following line will throw java.lang.UnsupportedOperationException
// immutableFruits.clear();
}
}
Output:
[Apple, Banana, Cherry] []
Explanation:
In the provided example:
1. We initiated an ArrayList of strings with three fruit names.
2. We then called the clear() method to remove all elements from the list, rendering the list empty.
3. The commented-out portion showcases a scenario where trying to clear an immutable list would lead to an UnsupportedOperationException.
The clear() method provides a quick way to discard all elements from a list and reset its size to zero, but caution is advised when working with immutable lists.
Related Java List methods
Java List add() example
Java List clear() example
Java List contains() example
Java List get() example
Java List indexOf() example
Java List remove() example
Java List size() example
Java List toArray() example
Comments
Post a Comment
Leave Comment