Java Utility Library

Java ArrayList - clear() Method



The java.util.ArrayList.clear() method is used to clear all elements of the ArrayList. This method makes the ArrayList empty with a size of zero.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.ArrayList.clear() method is used to clear all elements of the ArrayList called MyList.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    //printing ArrayList
    System.out.println("Before applying clear() method.");
    System.out.println("MyList contains: " + MyList);

    MyList.clear();

    //printing ArrayList
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("MyList contains: " + MyList);   
  }
}

The output of the above code will be:

Before applying clear() method.
MyList contains: [10, 20, 30]

After applying clear() method.
MyList contains: []

❮ Java.util - ArrayList