Java ArrayList.clear()

To remove all elements from an ArrayList in Java, call clear() method on the ArrayList.

In this tutorial, we will learn about the Java ArrayList.clear() method, and learn how to use this method to remove all the elements from this List and make it empty, with the help of examples.

clear()

ArrayList.clear() removes all of the elements from this ArrayList. The method empties the ArrayList.

ADVERTISEMENT

Syntax

The syntax of clear() method is

ArrayList.clear()

Returns

The method returns void.

Example 1 – clear()

In this example, we will create an ArrayList arrayList with four String elements in it. To make this ArrayList arrayList empty, we will call clear() method on this ArrayList.

Java Program

import java.util.ArrayList;
import java.util.Arrays;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
		System.out.println("ArrayList before clear : " + arrayList);
		arrayList.clear();
		System.out.println("ArrayList after clear  : " + arrayList);
    }
}

Output

ArrayList before clear : [a, b, c, d]
ArrayList after clear  : []

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList.clear() method, and also learnt how to use this method with the help of examples.