What is the ArrayList.clear() method in Java?

The ArrayList.clear() method in Java is used to remove all the elements from a list.

Syntax

The ArrayList.clear() method can be declared as shown in the code snippet below:

public void clear()

The ArrayList.clear() method takes in no parameter.

Return value

The ArrayList.clear() has no return value. It simply removes all the elements from the list and makes it empty.

Example

Consider the code snippet below, which demonstrates the use of the ArrayList.clear() method.

import java.util.ArrayList;
public class Example1 {
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>(5);
list1.add(72);
list1.add(48);
list1.add(12);
list1.add(9);
System.out.println("list1: " + list1);
System.out.println("list1.clear()");
list1.clear();
System.out.println("list1: " + list1);
}
}

Explanation

A list, list1, is declared in line 6. Four elements are added to list1 in lines 7-10 using the add() method. The ArrayList.clear() method is called in line 15, which removes all the elements from list1, leaving it empty.

Free Resources