How to clear an ArrayList in Java
In this tutorial, we are going to learn about how to clear or empty an ArrayList in Java.
Clearing an arraylist means removing the all elements from a given list.
Using clear() method
To clear an ArrayList, we can use the built-in clear() method of ArrayList
class in Java.
Here is an example, that removes all elements from a users
list:
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
ArrayList<String> users = new ArrayList<>(Arrays.asList("john", "kevin", "rose"));
users.clear(); //clears the list
System.out.println(users);
}
}
Ouput:
[]