Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

ArrayList clear() Method in Java with Examples

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so do whenever this operation has been performed all elements of the corresponding Arraylist will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimization.



Return Type: It does not return any value as it removes all the elements in the list and makes it empty. 

Tip: It does implement the following interfaces as follows: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

Example 1:


// Java Program to Illustrate Working of clear() Method
// of ArrayList class
// Importing required classes
import java.util.ArrayList;
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
        // Creating an empty Integer ArrayList
        ArrayList<Integer> arr = new ArrayList<Integer>(4);
        // Adding elements to above ArrayList
        // using add() method
        // Printing the elements inside current ArrayList
        System.out.println("The list initially: " + arr);
        // Clearing off elements
        // using clear() method
        // Displaying ArrayList elements
        // after using clear() method
            "The list after using clear() method: " + arr);


The list initially: [1, 2, 3, 4]
The list after using clear() method: []


New Example:-

In this example, we create a new ArrayList called animals and add some elements to it using the add() method. Then, we print the elements of the ArrayList.

Next, we call the clear() method to remove all elements from the ArrayList. Finally, we print the elements of the ArrayList again to demonstrate that it is now empty.


import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    // Create a new ArrayList
    ArrayList<String> animals = new ArrayList<>();
    // Add some elements to the ArrayList
    // Print the elements of the ArrayList
    System.out.println("Animals: " + animals);
    // Clear the ArrayList using the clear() method
    // Print the elements of the ArrayList after clearing it
    System.out.println("Animals after clearing: " + animals);


Animals: [Dog, Cat, Rabbit, Bird]
Animals after clearing: []

My Personal Notes arrow_drop_up
Last Updated : 30 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials