Java ArrayList removeAll() Method
The removeAll() method is used to remove elements in the dynamic array that exist in the specified collection.
The syntax of the removeAll() method is:
arraylist.removeAll(Collection c);
Note:arraylist is an object of the ArrayList class.
Parameter Description:
- c - The collection of elements to be removed from the dynamic array list
Return Value
Returns true if elements are successfully removed from the dynamic array.
Throws ClassCastException if the class of elements present in the dynamic array is incompatible with the element class of the specified collection.
Throws NullPointerException if the dynamic array contains null elements and the specified collection does not allow null elements.
Example
Remove all elements from the dynamic array list:
Example
class Main {
public static void main(String[] args){
// Create an array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Example");
sites.add("Taobao");
System.out.println("Website list: " + sites);
// Remove all elements
sites.removeAll(sites);
System.out.println("After all removeAll() methods: " + sites);
}
}
The output of running the above program is:
网站列表: [Google, Example, Taobao] 所有 removeAll() 方法后: []
In the above example, we created a dynamic array named sites. This dynamic array stores the names of websites.
Note this line:
sites.removeAll(sites);
sites is used as the parameter of the removeAll() method.
Note: clear() is the best way to remove all elements in a dynamic array. To learn more, please visitJava ArrayList clear()。
Other Extensions
Java ArrayList