Clear ArrayList java
Java ArrayList clear()The Java ArrayList clear() method removes all the elements from an arraylist. Show The syntax of the clear() method is: arraylist.clear()Here, arraylist is an object of the ArrayList class. clear() ParametersThe clear() method does not take any parameters. clear() Return ValueThe clear() method does not return any value. Rather, it makes changes to the arraylist. Example 1: Remove all elements from String Type ArrayListimport java.util.ArrayList; class Main { public static void main(String[] args){ // create an arraylist ArrayListOutput In the above example, we have created a arraylist named languages. The arraylist stores the name of programming languages. Here, we have used the clear() method to remove all the elements of languages. ArrayList clear() Vs. removeAll()The ArrayList also provides the removeAll() method that also remove all elements from the arraylist. For example, Output Odd Number ArrayList: [1, 3, 5] ArrayList after removeAll(): []In the above example, we have created an arraylist named oddNumbers. Here, we can see that the removeAll() method is used to remove all the elements from the arraylist. Both the removeAll() and clear() method are performing the same task. However, the clear() method is used more than removeAll(). It is because clear() is faster and efficient compared to removeAll(). To learn more about removeAll(), visit Java removeAll() method. |