YouTip LogoYouTip

Java Arraylist Clear

# Java ArrayList clear() Method [![Image 3: Java ArrayList](#) Java ArrayList](#) The `clear()` method is used to remove all elements from a dynamic array. The syntax of 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 sites =new ArrayList(); sites.add("Google"); sites.add(""); sites.add("Taobao"); System.out.println("Website List: "+ sites); // Remove all elements sites.clear(); System.out.println("After clear() method: "+ sites); } } The output of the above program is: Website List: [Google, , Taobao]After clear() method: [] In the example above, 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 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 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 using removeAll() method: "+ oddNumbers); } } The output of the above program is: Odd Numbers ArrayList: [1, 3, 5]After using removeAll() method: [] In the example above, 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 have the same functionality. However, the `clear()` method is more commonly used than `removeAll()` because `clear()` is faster and more efficient than `removeAll()`. To learn more about `removeAll()`, please visit [Java ArrayList removeAll() Method](#). [![Image 4: Java ArrayList](#) Java ArrayList](#)
← Java Arraylist ClonePython3 String Swapcase β†’