VOOZH about

URL: https://www.geeksforgeeks.org/java/collection-clear-method-in-java-with-examples/

⇱ Collection clear() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collection clear() method in Java with Examples

Last Updated : 11 Jul, 2025

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.

Example:

Output:

List before clearing: [1, 2, 3, 4]
List after clearing: []

Syntax

Collection.clear()

Parameters:

  • This method does not accept any parameter

Returns:

  • This method does not return any value.

Exceptions:

  • UnsupportedOperationException: if the add operation is not supported by this collection

Collection clear() Method Examples

Let's see some examples of how to use the collection clear() method in Java.

Example 1:

How to remove all elements from a collection using collection clear() Method


Output
The list is: [Geeks, for, Geeks]
The new List is: []

Example 2:

Using the clear() method on ArrayDeque to remove its elements.


Output
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The new ArrayDeque is: []

Example 3:

Using the clear() method on ArrayList


Output
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
Comment