Java ArrayList clear() Method

Java ArrayList Java ArrayList

clear() method is used to delete all elements in the dynamic array.

The syntax of the clear() method is:

arraylist.clear()

Note:arraylist is an object of the ArrayList class.

Parameter Description:

  • None

Example

Use ArrayList clear() to delete all elements:

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("Example");
        sites.add("Taobao");
        System.out.println("Website list: " + sites);

        // Delete all elements
        sites.clear();
        System.out.println("After all clear() methods: " + sites);
    }
}

Executing the above program outputs the result:

网站列表: [Google, Example, Taobao]
所有 clear() 方法后: []

In the above example, we created a dynamic array named sites. This dynamic array stores the names of websites.

At the end of the example, we used the clear() method to delete all elements of the dynamic array sites.

clear() and removeAll() Methods

The dynamic array also provides the removeAll() method, which can also delete all elements in the array, as follows:

Example

import java.util.ArrayList;

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

        // Create a dynamic array
        ArrayList<Integer> oddNumbers = new ArrayList<>();

        // Add elements to the dynamic array
        oddNumbers.add(1);
        oddNumbers.add(3);
        oddNumbers.add(5);
        System.out.println("Odd ArrayList: " + oddNumbers);

        // Delete all elements
        oddNumbers.removeAll(oddNumbers);
        System.out.println("After using the removeAll() method: " + oddNumbers);
    }
}

Executing the above program outputs the result:

奇数 ArrayList: [1, 3, 5]
使用 removeAll() 方法后: []

In the above example, we created a dynamic array named oddNumbers, and then used the removeAll() method to delete all elements in the array.

The removeAll() and clear() methods have the same functionality. However, clear() is more commonly used than removeAll() because clear() is faster and more efficient than removeAll().

To learn more about removeAll(), please visitJava ArrayList removeAll() Method。

Java ArrayList Java ArrayList

Other Extensions