Open In App

Java Program to Empty an ArrayList in Java

Last Updated : 14 Dec, 2021
Comments
Improve
Suggest changes
1 Like
Like
Report

ArrayList class is a resizable array, present in 'java.util package'. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array.

Approaches :

  1. Using clear() method.
  2. Using removeAll() method.

Method 1: Using clear() method as the clear() method of ArrayList in Java is used to remove all the elements from an ArrayList. The ArrayList will be completely empty after this call returns.

Syntax: 

public void clear() ;

Parameters: clear function takes no parameter

Return Value: This method does not return any value.

Exception: NA

Example:


Output
Numbers ArrayList : [10, 20, 30, 40]
Numbers ArrayList consists of 4 elements
Performing clear operation by using clear function
Finally Numbers ArrayList consists of 0 elements

Method 2: Using removeAll() method as this method of ArrayList class is used to remove from this list all of its elements that are contained in the specified collection.

Syntax:

public boolean removeAll(Collection c) ;

Parameters: This method takes collection c as a parameter containing elements to be removed from this list.

Return Value: This method returns true if this list changed as a result of the call.

Exception/s: This method throws NullPointerException if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.

Example:


Output
Numbers ArrayList : [10, 20, 30, 40]
Numbers ArrayList consists of 4 elements
Performing clear operation by using clear function
Finally Numbers ArrayList consists of 0 elements

Next Article
Practice Tags :

Similar Reads