Easy Tutorial
❮ Arrays Reverse Java Basic Datatypes ❯

Java ArrayList removeAll() Method

Java ArrayList

The removeAll() method is used to remove elements from the dynamic array that are present in the specified collection.

The syntax for the removeAll() method is:

arraylist.removeAll(Collection c);

Note: arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

Returns true if elements are successfully removed from the dynamic array.

Throws ClassCastException if the class of an element in the dynamic array is incompatible with the specified collection.

Throws NullPointerException if the dynamic array contains a null element and the specified collection does not permit null elements.

Example

Remove all elements from the dynamic array list:

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args){

        // Create an array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("tutorialpro");
        sites.add("Taobao");
        System.out.println("Website List: " + sites);

        // Remove all elements
        sites.removeAll(sites);
        System.out.println("After using removeAll() method: " + sites);
    }
}

Executing the above program outputs:

Website List: [Google, tutorialpro, Taobao]
After using removeAll() method: []

In the above example, we created a dynamic array named sites which stores website names.

Notice this line:

sites.removeAll(sites);

sites is passed as an argument to the removeAll() method.

Note: clear() is the best method to remove all elements from a dynamic array. For more information, visit Java ArrayList clear().

Java ArrayList

❮ Arrays Reverse Java Basic Datatypes ❯