English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList clear() method removes all elements from the arraylist.
The syntax of the clear() method is:
arraylist.clear()
The clear() method does not take any parameters.
The clear() method does not return any value. It clears the arraylist.
import java.util.ArrayList; class Main { public static void main(String[] args){ //Create arraylist ArrayList<String> languages = new ArrayList<>(); languages.add("Java"); languages.add("JavaScript"); languages.add("Python"); System.out.println("Programming languages: "); + languages); //Delete All Elements languages.clear(); System.out.println("ArrayList after clear(): "); + languages); } }
Output Result
Programming languages: [Java, JavaScript, Python] ArrayList after clear(): []
In the above example, we created an ArrayList named languages. The arraylist stores the names of programming languages.
Here, we have used the clear() method to remove all elements from languages.
ArrayList also provides the removeAll() method, which removes all elements from the arraylist. For example,
import java.util.ArrayList; class Main { public static void main(String[] args){ // Create arraylist ArrayList<Integer> oddNumbers = new ArrayList<>(); // Add elements to the arraylist oddNumbers.add(1);}} oddNumbers.add(3);}} oddNumbers.add(5);}} System.out.println("Odd ArrayList: " + oddNumbers); // Delete All Elements oddNumbers.removeAll(oddNumbers); System.out.println("ArrayList after removeAll(): " + oddNumbers); } }
Output Result
Odd ArrayList: [1, 3, 5] ArrayList after removeAll(): []
In the above example, we created an ArrayList named oddNumbers. Here, we can see that the removeAll() method is used to delete all elements from the arraylist.
The removeAll() and clear() methods perform the same task. However, the usage rate of clear() is higher than that of removeAll(). This is because clear() is faster and more efficient than removeAll().