How To Empty An Arraylist In Java
Last Updated : Mar 11, 2024
In this article we will show you the solution of how to empty an arraylist in java, the ArrayList.removeAll() method can be used to empty an array list without using another array list.clear() method.
It is worth noting that both methods do the same thing, but the way in which they empty the List is slightly different.
An ArrayList can be reset in order to empty the entire array or to remove all of its elements.
We do this for reusing an ArrayList. An ArrayList may be reset in Java by calling clear() or removing all elements from it.
If the size of your ArrayList, i.e. it contains only 10 or 100 elements, you should not need to worry too much about using either of these two methods; however, if you have an array list with tens of thousands of elements, then clear() vs removeAll() may have a significant impact on the performance of your Java application if there are tens of thousands of entries.
We will now discuss the idea of how to empty an arraylist in java with an example.
Step By Step Guide On How To Empty An Arraylist In Java :-
package talkerscode.com; import java.util.ArrayList; import java.io.*; public class TalkersCode { public static void main(String [] args) { Arraylist<String> AL1=new Arraylist<String>(); AL1.add("abc"); AL1.add("xyz"); System.out.println("ArrayList before clear: "+AL1); AL1.clear(); System.out.println("ArrayList after clear: "+AL1); ArrayList<String> AL2=new ArrayList<String>(); AL2.add("text 1"); AL2.add("text 2"); System.out.println("ArrayList before removeAll: "+AL2); AL2.removeAll(AL2); System.out.println("ArrayList before removeAll: "+AL2); } }
- First we import the necessary modules, which includes ArrayList and input/output classes in Java.
- Then we create a class named "TalkersCode".
- After we define the main function.
- We declare and initialize an ArrayList called "AL1" containing two strings: "abc" and "xyz".
- We print out the ArrayList before clearing it.
- We use the clear() method to delete all elements in the ArrayList.
- We print out the ArrayList after clearing it.
- We declare and initialize a second ArrayList called "AL2" containing two strings: "text 1" and "text 2".
- We print out the ArrayList before removing all elements.
- We use the removeAll() method to remove all elements from the ArrayList.
- We print out the ArrayList after removing all elements.
Conclusion :-
As a result, we have successfully learned how to empty an arraylist in java with an example.
The clear() method should be used in place of creating and assigning a new ArrayList when we need to remove information from an ArrayList.
The article ends with an explanation of the Array and the ArrayList clear() method and the ArrayList removeAll() method.
I hope this article on how to empty an arraylist in java helps you and the steps and method mentioned above are easy to follow and implement.