Skip to content
Related Articles
Open in App
Not now

Related Articles

ArrayList clear() Method in Java with Examples

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 13 May, 2022
Improve Article
Save 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.

Syntax: 

clear()

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




// 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
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
 
        // Printing the elements inside current ArrayList
        System.out.println("The list initially: " + arr);
 
        // Clearing off elements
        // using clear() method
        arr.clear();
 
        // Displaying ArrayList elements
        // after using clear() method
        System.out.println(
            "The list after using clear() method: " + arr);
    }
}

Output: 

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

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!