How to remove all elements of ArrayList in Java?

JavaObject Oriented ProgrammingProgramming

The List interface extends Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Unlike sets, list allows duplicate elements, allows multiple null values if null value is allowed in the list. List provides add, remove methods to add/remove elements. In order to clear a list or remove all the elements from the list, we can use clear() method of the List. We can also use removeAll() method as well to achive the same effect as clear() method.

In this article, we're going to cover clear() and removeAll() methods with corresponding examples.

Syntax - clear() method

void clear()

Notes

  • Removes all of the elements from this list.

  • The list will be empty after this call returns.

Throws

  • UnsupportedOperationException - If the clear operation is not supported by this list.

Syntax - removeAll() method

boolean removeAll(Collection<?> c)

Removes from this list all of its elements that are contained in the specified collection.

Parameters

  • c - collection containing elements to be removed from this list.

Returns

True if this list changed as a result of the call

Throws

  • UnsupportedOperationException - If the removeAll operation is not supported by this list.

  • ClassCastException - If the class of an element of this list is incompatible with the specified collection (optional).

  • 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 1

Following is the example showing the usage of clear() method −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
      System.out.println("List: " + list);
      list.clear();
      System.out.println("Cleared List: " + list);
   }
}

Output

This will produce the following result −

List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Cleared List: []

Example 2

Following is the example showing the usage of removeAll() method −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
      System.out.println("List: " + list);
      list.removeAll(list);
      System.out.println("Cleared List: " + list);
   }
}

Output

This will produce the following result −

List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Cleared List: []
raja
Updated on 26-May-2022 13:17:24

Advertisements