How to remove all elements from arraylist in java

Let’s learn how to remove all elements from arraylist in java.

How to remove all elements from arraylist in java

We can remove all elements from arraylist in two ways. One using clear() method and other using removeAll() method.

Both clear() and removeAll() method are defined in java.util.List and java.util.Collection interface.

clear() method removes all of the elements from this list. The list willbe empty after this call returns.

The time taken to remove all elements from ArrayList using clear() method is O(n).

removeAll() method removes from this list all of its elements that are contained in thespecified collection.

The time taken to remove all elements from ArrayList using remveAll() method is O(n ^ 2).

Let’s see an example.

import java.util.ArrayList;
public class RemoveAllElements
{
   public static void main(String[] args)
   {
      ArrayList<String> fruits = new ArrayList<>();
      fruits.add("pineapple");
      fruits.add("orange");
      fruits.add("apple");
      fruits.add("banana");
      fruits.add("watermelon");
      System.out.println("ArrayList before using clear() method: ");
      System.out.println(fruits);
      // empty an ArrayList using clear() method
      fruits.clear();
      System.out.println("ArrayList after using clear() method: ");
      System.out.println(fruits);
      ArrayList<String> colors = new ArrayList<>();
      colors.add("red");
      colors.add("blue");
      colors.add("green");
      colors.add("white");
      System.out.println("ArrayList before using removeAll() method: ");
      System.out.println(colors);
      // empty an ArrayList using removeAll() method
      colors.removeAll(colors);
      System.out.println("ArrayList after using removeAll() method: ");
      System.out.println(colors);
   }
}


Output:

ArrayList before using clear() method: [pineapple, orange, apple, banana, watermelon]
ArrayList after using clear() method: []
ArrayList before using removeAll() method: [red, blue, green, white]
ArrayList after using removeAll() method: []


Also read – java overview