Java ArrayList clear() Method
The clear() method is used to remove all elements from the dynamic array.
The syntax for the clear() method is:
arraylist.clear()
Note: arraylist is an object of the ArrayList class.
Parameter Description:
- None
Example
Using ArrayList clear() to remove 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("tutorialpro");
sites.add("Taobao");
System.out.println("Website List: " + sites);
// Remove all elements
sites.clear();
System.out.println("After clear() method: " + sites);
}
}
Executing the above program outputs:
Website List: [Google, tutorialpro, Taobao]
After clear() method: []
In the above example, we created a dynamic array named sites that stores website names.
At the end of the example, we used the clear() method to remove all elements from the dynamic array sites.
clear() vs removeAll() Method
The dynamic array also provides the removeAll() method, which can also remove all elements from the array, as shown below:
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 Numbers ArrayList: " + oddNumbers);
// Remove all elements
oddNumbers.removeAll(oddNumbers);
System.out.println("After removeAll() method: " + oddNumbers);
}
}
Executing the above program outputs:
Odd Numbers ArrayList: [1, 3, 5]
After removeAll() method: []
In the above example, we created a dynamic array named oddNumbers and then used the removeAll() method to remove all elements from the array.
Both removeAll() and clear() methods serve the same purpose. However, the clear() method is more commonly used than removeAll() because clear() is faster and more efficient.
To learn more about removeAll(), visit Java ArrayList removeAll() Method.