Remove all elements from the ArrayList in Java

JavaObject Oriented ProgrammingProgramming

To remove all elements from ArrayList in Java, let us first create an ArrayList with some elements −

ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
arrlist.add(25);
arrlist.add(50);
arrlist.add(75);
arrlist.add(100);
arrlist.add(150);
arrlist.add(200);
arrlist.add(250);

Now, let us remove all the elements −

arrlist.clear();

Example

Let us now see the complete code −

 Live Demo

import java.util.ArrayList;
public class Demo {
   public static void main(String[] args) {
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
      arrlist.add(25);
      arrlist.add(50);
      arrlist.add(75);
      arrlist.add(100);
      arrlist.add(150);
      arrlist.add(200);
      arrlist.add(250);
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }
      int retval = arrlist.size();
      System.out.println("List consists of "+ retval +" elements");
      System.out.println("Performing clear operation!!");
      arrlist.clear();
      retval = arrlist.size();
      System.out.println("Now, list consists of "+ retval +" elements");
   }
}

Output

This will produce the following output −

Number = 25
Number = 50
Number = 75
Number = 100
Number = 150
Number = 200
Number = 250
List consists of 7 elements
Performing clear operation!!
Now, list consists of 0 elements
raja
Published on 02-Jan-2020 11:14:43
Advertisements