Difference between ArrayList.clear() and ArrayList.removeAll() in java?


The ArrayList class in Java is a Resizable-array implementation of the List interface. It allows null values.

The clear() method this class removes all the elements from the current List object.

Example

 Live Demo

import java.util.ArrayList;
public class ClearExample {
   public static void main(String[] args){
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      list.clear();
      System.out.println("Contents of the ArrayList object after invoking the clear() method: "+list);
   }
}

Output

Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, Impala]
Contents of the ArrayList object after invoking the clear() method: []

Whereas, the removeAll() method of the ArrayList class accepts another collection object as a parameter and removes all the contents of it from the current ArrayList.

Example

 Live Demo

import java.util.ArrayList;
public class ClearExample {
   public static void main(String[] args){
      //Instantiating an ArrayList object
      ArrayList<String> list1 = new ArrayList<String>();
      list1.add("JavaFX");
      list1.add("Java");
      list1.add("WebGL");
      list1.add("OpenCV");
      list1.add("OpenNLP");
      list1.add("JOGL");
      list1.add("Hadoop");
      list1.add("HBase");
      list1.add("Flume");
      list1.add("Mahout");
      list1.add("Impala");
      System.out.println("Contents of the Array List1 : \n"+list1);
      ArrayList<String> list2 = new ArrayList<String>();
      list2.add("JOGL");
      list2.add("Hadoop");
      list2.add("HBase");
      list2.add("Flume");
      list2.add("Mahout");
      list2.add("Impala");
      System.out.println("Contents of the Array List1 : \n"+list2);
      //Removing elements
      list1.removeAll(list2);
      System.out.println("Contents of the Array List after removal: \n"+list1);
   }
}

Output

Contents of the Array List1 :
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List1 :
[JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List after removal:
[JavaFX, Java, WebGL, OpenCV, OpenNLP]
raja
Published on 15-Oct-2019 10:20:18
Advertisements