Remove all objects in java

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.

Читайте также:  Css font background height

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 crate thread-safety-related problems and erroneous results.

See Core Java for the Impatient to learn more about the problems of using ArrayList in muti-threading 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 AraryList */ public class Main < public static void main(String[] args) < System.out.println("Welcome to Java Program to empty an ArrayList"); ArrayList listOfInsurance = new ArrayList<>(); listOfInsurance.add("Car Insurnace"); listOfInsurance.add("Health Insurnace"); 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 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 Insurnace, Health Insurnace, 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.

  • 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)

Источник

How to remove all elements of ArrayList in Java?

The List interface extends Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Unlike sets, list allows duplicate elements, allows multiple null values if null value is allowed in the list. List provides add, remove methods to add/remove elements. In order to clear a list or remove all the elements from the list, we can use clear() method of the List. We can also use removeAll() method as well to achive the same effect as clear() method.

In this article, we’re going to cover clear() and removeAll() methods with corresponding examples.

Syntax — clear() method

Notes

  • Removes all of the elements from this list.
  • The list will be empty after this call returns.

Throws

  • UnsupportedOperationException — If the clear operation is not supported by this list.

Syntax — removeAll() method

boolean removeAll(Collection c)

Removes from this list all of its elements that are contained in the specified collection.

Parameters

Returns

True if this list changed as a result of the call

Throws

  • UnsupportedOperationException — If the removeAll operation is not supported by this list.
  • ClassCastException — If the class of an element of this list is incompatible with the specified collection (optional).
  • NullPointerException — If this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.

Example 1

Following is the example showing the usage of clear() method −

package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Listlist = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9)); System.out.println("List: " + list); list.clear(); System.out.println("Cleared List: " + list); > >

Output

This will produce the following result −

List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Cleared List: []

Example 2

Following is the example showing the usage of removeAll() method −

package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Listlist = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9)); System.out.println("List: " + list); list.removeAll(list); System.out.println("Cleared List: " + list); > >

Output

This will produce the following result −

List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Cleared List: []

Источник

Оцените статью