Clear an ArrayList in Java


An ArrayList can be cleared in Java using the method java.util.ArrayList.clear(). This method removes all the elements in the ArrayList. There are no parameters required by the ArrayList.clear() method and it returns no value.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("Orange");
      aList.add("Apple");
      aList.add("Peach");
      aList.add("Guava");
      aList.add("Mango");
      System.out.println("ArrayList before using the ArrayList.clear() method: " + aList);
      aList.clear();
      System.out.println("ArrayList after using the ArrayList.clear() method: " + aList);
   }
}

Output

ArrayList before using the ArrayList.clear() method: [Orange, Apple, Peach, Guava, Mango]
ArrayList after using the ArrayList.clear() method: []

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. The ArrayList is displayed before and after using the ArrayList.clear() method which clears the ArrayList. A code snippet which demonstrates this is as follows −

List aList = new ArrayList();
aList.add("Orange");
aList.add("Apple");
aList.add("Peach");
aList.add("Guava");
aList.add("Mango");
System.out.println("ArrayList before using the ArrayList.clear() method: " + aList);
aList.clear();
System.out.println("ArrayList after using the ArrayList.clear() method: " + aList);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

615 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements