ArrayList clear() method in java

Let’s learn ArrayList clear() method in java.

ArrayList clear() method in java

clear() method of ArrayList class removes all of the elements from this list. The list will be empty after this call returns.

Syntax:

clear()

Parameters:

this method has no parameters.

Returns:

clear() method do not return any value.

Also read – ArrayList in java

Now let’s see example on ArrayList clear() method.

import java.util.ArrayList;
public class ArrayListClearMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>(4);
      al.add(9);
      al.add(3);
      al.add(5);
      al.add(1);
      System.out.println("ArrayList before clear() method: " + al);
      al.clear();
      System.out.println("ArrayList after clear() method: " + al);
   }
}


Output:

ArrayList before clear() method: [9, 3, 5, 1]
ArrayList after clear() method: []