Skip to Content

Remove all elements from Java ArrayList Example

  1. /*
  2.   Remove all elements from Java ArrayList Example
  3.   This Java Example shows how to remove all elements from java ArrayList object
  4.   using clear method.
  5. */
  6.  
  7. import java.util.ArrayList;
  8.  
  9. public class RemoveAllElementsOfArrayListExample {
  10.  
  11.   public static void main(String[] args) {
  12.     //create an ArrayList object
  13.     ArrayList arrayList = new ArrayList();
  14.    
  15.     //Add elements to Arraylist
  16.     arrayList.add("1");
  17.     arrayList.add("2");
  18.     arrayList.add("3");
  19.    
  20.     System.out.println("Size of ArrayList before removing elements : "
  21.                                                        + arrayList.size());
  22.     /*
  23.       To remove all elements from the ArrayList use
  24.       void clear() method.
  25.     */
  26.     arrayList.clear();
  27.     System.out.println("Size of ArrayList after removing elements : "
  28.                                                        + arrayList.size());
  29.    
  30.   }
  31. }
  32. /*
  33. Output would be
  34. Size of ArrayList before removing elements : 3
  35. Size of ArrayList after removing elements : 0
  36. */