The syntax of the removeAll() method is:
arraylist.removeAll(Collection c);
Here, arraylist is an object of the ArrayList class.
removeAll() Parameters
The removeAll() method takes a single parameter.
- collection -all elements present in collection are deleted from the arraylist.
removeAll() Return Value
- returns
trueif elements are deleted from the arraylist - throws
ClassCastExceptionif the class of elements present in arraylist is incompatible with the class of elements in specified collection - throws
NullPointerExceptionif the arraylist contains null element and the specified collection does not allow null elements
Example 1: Remove all elements from an ArrayList
Output
Programming Languages: [Java, JavaScript, Python] ArrayList after removeAll(): []
In the above example, we have created an arraylist named languages. The arraylist stores the name of programming languages. Notice the line,
languages.removeAll(languages);
Here, we are passing the ArrayList languages as an argument of the removeAll() method. Hence, the method removes all the elements from the arraylist.
Note: The clear() method is preferred to remove all elements from the arraylist. To know more, visit Java ArrayList clear().
Example 2: Remove all Elements from an ArrayList Present in Another ArrayList
Output
Languages1: [Java, English, C, Spanish] Languages2: [English, Spanish] Languages1 after removeAll(): [Java, C]
In the above example, we have created two arraylists named languages1 and languages2. Notice the line,
languages1.removeAll(languages2);
Here, the removeAll() method is used to remove all those elements from languages1 that are also present in languages2. Hence, English and Spanish are removed from languages1.
Example 3: Remove all Elements from an ArrayList Present in a HashSet
Output
ArrayList: [1, 2, 3, 4] HashSet: [2, 3] ArrayList after removeAll(): [1, 4]
In the above example, we have created an arraylist named numbers and a hashset named primeNumbers. Notice the line,
numbers.removeAll(primeNumbers);
Here, the removeAll() method removes all those elements from numbers that are also present in primeNumbers. Hence, 2 and 3 are removed from the arraylist numbers.