Clear an ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

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);
raja
Published on 10-Jan-2019 09:18:50
Advertisements