Saturday, September 30, 2023

How to remove all elements of ArrayList in Java - RemoveAll Example

There are two ways to remove all elements of an ArrayList in Java, either by using clear() or by using the removeAll() method. Both methods are defined in the java.util.List and java.util.Collection interface, hence they are available not just to ArrayList but also to Vector or LinkedList, etc. Both elements remove all objects from ArrayList but there is a subtle difference in how they do. The clear() method is straightforward, it traverses through the ArrayList and sets all indices to null, which means the ArrayList becomes empty and all elements become eligible to Garbage collection, provided there are no more references to them.

 The time taken by the clear() method is in O(n), which means the bigger the ArrayList the longer it will take to empty it.

On the other hand, removeAll(Collection c) accepts a Collection and then iterate over List. At each iteration, it checks if the current element in the ArrayList is present in the Collection c using contains() method, which takes its O(n) time to confirm because it also uses Iterator instead of random access.

So overall time taken to remove all elements using the removeAll() method is in order of O(n^2) which means time will increase in the quadratic of a number of elements in the array

This difference is not much if your ArrayList is small and just contains 10 to 100 elements but for a big ArrayList e.g. of 1 million objects, this time could be significant.

This is also one of the frequently asked ArrayList questions from Java Interviews, so knowing the key difference will help you there as well.  So the choice is yours, I suggest using clear() if you want to remove all elements from the ArrayList and use removeAll() if you want to remove selected elements given to you in a Collection

. Let's see the example of both of them in Java.




How to empty an ArrayList in Java? Example

Here is a complete Java program to remove all elements and make an ArrayList empty in Java. This program demonstrates how you can remove all elements from a given ArrayList by using both the clear() and removeAll() methods.

If you want to remove just a single element then you can use the remove() method as discussed here.

The program prints all objects of ArrayList before and after calling the clear() and removeAll() method to show that method is actually working and the ArrayList is empty afterward.

You can reuse the ArrayList by clearing it but make sure you don't do that in a multi-threading environment e.g. one thread is calling the clear() method while another thread is calling the add() method to insert elements.  

The ArrayList class is not thread-safe and sharing the same ArrayList between multiple threads will create thread-safety-related problems and erroneous results. See Core Java for the Impatient to learn more about the problems of using ArrayList in multithreading applications.

How to empty an ArrayList in Java? Example




Java Program to make an ArrayList empty

Here is our complete Java program to demonstrate how to remove all elements from a give ArrayList in Java using the removeAll method.

import java.util.ArrayList;

/*
 * Java Program to remove all elements of ArrayList.
 * This is also known as emptying an ArrayList
 */

public class Main {

  public static void main(String[] args) {
    System.out.println("Welcome to Java Program to empty an ArrayList");

    ArrayList<String> listOfInsurance = new ArrayList<>();

    listOfInsurance.add("Car Insurance");
    listOfInsurance.add("Health Insurance");
    listOfInsurance.add("Life Insurance");
    listOfInsurance.add("Home Furniture Insurance");
    listOfInsurance.add("Home loan Insurance");

    System.out.println("ArrayList before emptying: ");
    System.out.println(listOfInsurance);

    // Emptying an ArrayList in Java
    listOfInsurance.clear();

    System.out.println("ArrayList after emptying: ");
    System.out.println(listOfInsurance);

    ArrayList<String> listOfLoans = new ArrayList<>();

    listOfLoans.add("Car loan");
    listOfLoans.add("Persona loan");
    listOfLoans.add("Balance transfer");
    listOfLoans.add("Home loan");

    System.out.println("ArrayList before removing all elements: ");
    System.out.println(listOfLoans);

    // Emptying an ArrayList in Java
    listOfLoans.removeAll(listOfLoans);

    System.out.println("ArrayList after removing all elements: ");
    System.out.println(listOfLoans);
  }

}

Output
Welcome to Java Program to empty an ArrayList
ArrayList before emptying: 
[Car Insurance, Health Insurance, Life Insurance, Home Furniture Insurance,
Home loan Insurance]
ArrayList after emptying: 
[]
ArrayList before removing all elements: 
[Car loan, Persona loan, Balance transfer, Home loan]
ArrayList after removing all elements: 
[]

You can see that both the ArrayLists are empty after calling the clear() and removeAll() methods. So it's working!!

That's all about how to remove all elements from an ArrayList in Java. As I said, clear() takes less time than removeAll() to remove all objects, hence you should always use clear() to make an ArrayList empty. But, if you are not removing all elements and a list of elements to be removed are provided to you in a Collection or List then use the removeAll() method.

Other Java ArrayList tutorials for Java Programmers
  • How to loop over ArrayList in Java? (answer)
  • How to create and initialize the ArrayList in one line? (answer)
  • How to sort an ArrayList in Java? (answer)
  • How to convert an ArrayList to String in Java? (example)
  • How to remove duplicates from ArrayList in Java? (example)
  • How to reverse an ArrayList in Java? (solution)
  • How to get the first and last element of ArrayList in Java? (solution)
  • How to declare ArrayList with values in Java? (example)
  • How to get a range of elements as sublists from ArrayList in Java? (example)
  • How convert ArrayList to HashSet in Java? (example)

Now one question for you? Which method do you us to remove all elements from a List or Set in Java? clear() or removeAll() ?

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.