Clear or Delete all the Elements of ArrayList

To remove all the elements of ArrayList, you can use ArrayList.clear() method. ArrayList.clear() removes all the elements from ArrayList and makes it empty. Or you can use ArrayList.removeAll() with the same ArrayList passed as argument.

After removing all the elements, you will get the size of ArrayList as zero.

Example 1 – Empty an ArrayList using ArrayList.clear()

In this example, we will create an ArrayList with some elements, and then call clear() method on the ArrayList to empty the ArrayList.

Java Program

</>
Copy
import java.util.ArrayList;

public class Example {
  public static void main(String[] args) {
	  ArrayList<String> arrayList = new ArrayList<String>();  
	  arrayList.add("a");  
	  arrayList.add("b");  
	  arrayList.add("c"); 
	  arrayList.add("d");
	  arrayList.add("e");
	  System.out.println("Original ArrayList  : " + arrayList);
	  
	  arrayList.clear();
	  System.out.println("Resulting ArrayList : " + arrayList);
  }
}

Output

Original ArrayList  : [a, b, c, d, e]
Resulting ArrayList : []

Example 2 – Empty an ArrayList using ArrayList.removeAll()

In this example, we will create an ArrayList with some elements, and then call removeAll() method with the same ArrayList passed as argument.

Java Program

</>
Copy
import java.util.ArrayList;

public class Example {
  public static void main(String[] args) {
	  ArrayList<String> arrayList = new ArrayList<String>();  
	  arrayList.add("a");  
	  arrayList.add("b");  
	  arrayList.add("c"); 
	  arrayList.add("d");
	  arrayList.add("e");
	  System.out.println("Original ArrayList  : " + arrayList);
	  
	  arrayList.removeAll(arrayList);
	  System.out.println("Resulting ArrayList : " + arrayList);
  }
}

Output

Original ArrayList  : [a, b, c, d, e]
Resulting ArrayList : []

Conclusion

In this Java Tutorial, we learned how to clear, empty or delete all the elements of an ArrayList, with the help of example programs.