Java Collection Tutorial - Java ArrayList.clear()








Syntax

ArrayList.clear() has the following syntax.

public void clear()

Example

In the following code shows how to use ArrayList.clear() method.

/*from   ww  w.  ja v a2 s.c  o  m*/
import java.util.ArrayList;

public class Main {
   public static void main(String[] args) {
      ArrayList<Integer>  arrlist = new ArrayList<Integer> (5);

      // use add() method to add elements in the list
      arrlist.add(20);
      arrlist.add(30);
      arrlist.add(10);
      arrlist.add(50);

      System.out.println(arrlist);
      
      // finding size of this list
      int retval = arrlist.size();
      System.out.println("List consists of "+ retval +" elements");
      
      arrlist.clear();
      retval = arrlist.size();
      System.out.println("list consists of "+ retval +" elements");
   }
}

The code above generates the following result.