![]() |
VOOZH | about |
The collection clear() method of Java Collection Interface clears the Collection upon which it is called. After this method is called, the collection will be empty as it removes all the elements from the collection.
This method does not take any parameter and does not return any value.
Output:
List before clearing: [1, 2, 3, 4]
List after clearing: []
Collection.clear()Let's see some examples of how to use the collection clear() method in Java.
How to remove all elements from a collection using collection clear() Method
The list is: [Geeks, for, Geeks] The new List is: []
Using the clear() method on ArrayDeque to remove its elements.
ArrayDeque: [Welcome, To, Geeks, 4, Geeks] The new ArrayDeque is: []
Using the clear() method on ArrayList
ArrayList: [15, 20, 25] The new ArrayList is: []
Reference: Official Oracle Documents
Whether you are a beginner starting Java programming or an experienced looking to brush up on your Java skills, this tutorial will provide you with a deep understanding of the collection clear function and its uses in Java.
The clear method in Java is a fundamental function for collection manipulation. With this guide, you can easily remove all elements of a collection using the clear function.
Read More Collection Methods