Delete ArrayList Java

The remove() method removes the single element from the arraylist.

Example

import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<Integer> primeNumbers = new ArrayList<>(); primeNumbers.add(2); primeNumbers.add(3); primeNumbers.add(5); System.out.println("ArrayList: " + primeNumbers);

// remove element at index 2 int removedElement = primeNumbers.remove(2);

System.out.println("Removed Element: " + removedElement); } } // Output: ArrayList: [2, 3, 5] // Removed Element: 5

The syntax of the remove() method is:

// remove the specified element arraylist.remove(Object obj) // remove element present in the specified index arraylist.remove(int index)

Here, arraylist is an object of the ArrayList class.

remove() Parameters

The remove() method takes a single parameter.

  • obj - element that is to be removed from the arraylist, OR
  • index - position from where element is to be removed

If the same element obj is present in multiple location, then the element that appear first in the arraylist is removed.

remove() Return Value

  • returns true if specified element is present in the arraylist
  • returns the removed element if index is passed as parameter

Note: If the specified index is out of range, the method throws IndexOutOfBoundsException.

Example 1: Remove the Specified Element from the ArrayList

import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<String> languages = new ArrayList<>(); // insert element to the arraylist languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("ArrayList: " + languages);

// remove the element Java boolean result = languages.remove("Java");

System.out.println("Is element Java removed? " + result); System.out.println("ArrayList after remove(): " + languages); } }

Output

ArrayList: [JavaScript, Java, Python] Is element Java removed? true ArrayList after remove(): [JavaScript, Python]

In the above example, we have created a arraylist named languages. The arraylist stores the name of programming languages.

Here, we have used the remove() method to remove the element Java from the arraylist.

Example 2: Remove the Element From the Specified Position

import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<String> languages = new ArrayList<>(); // insert element to the arraylist languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("ArrayList: " + languages);

// remove the element from position 2 String element = languages.remove(2);

System.out.println("ArrayList after remove(): " + languages); System.out.println("Removed Element: " + element); } }

Output

ArrayList: [JavaScript, Java, Python] ArrayList after remove(): [JavaScript, Java] Removed Element: Python

In the above example, we have created an arraylist named languages. Notice the expression,

languages.remove(2)

Here, the remove() returns and removes the element present at position 2 (i.e. Python).

Example 3: Remove the First Occurrence of the Element

import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<Integer> randomNumbers = new ArrayList<>(); // add element to the arraylist randomNumbers.add(22); randomNumbers.add(13); randomNumbers.add(35); randomNumbers.add(13); randomNumbers.add(40); System.out.println("ArrayList: " + randomNumbers);

// remove the first occurrence of 13 boolean result = randomNumbers.remove(Integer.valueOf(13));

System.out.println("Is element 13 removed? " + result); System.out.println("ArrayList after remove(): " + randomNumbers); } }

Output

ArrayList: [22, 13, 35, 13, 40] Is element 13 removed? true ArrayList after remove(): [22, 35, 13, 40]

In the above example, we have created an arraylists named randomNumbers . In the arraylist, the element 13 is present in two locations. Notice the line,

randomNumbers.remove(Integer.valueOf(13))

Here,

  • Integer.valueOf() - Converts the int value 13 to an Integer object. It is because the remove() method only takes objects as its arguments. To learn more, visit Java Primitive Types to Wrapper Objects.
  • remove() - Removes the element 13 that appeared first in the arraylist.

Note: We can also remove all the elements from the arraylist using the clear() method. To learn more, visit Java ArrayList clear().

Java List remove() method is used to remove elements from the list. ArrayList is the most widely used implementation of the List interface, so the examples here will use ArrayList remove() methods.

Java List remove() Methods

There are two remove() methods to remove elements from the List.

  1. E remove(int index): This method removes the element at the specified index and return it. The subsequent elements are shifted to the left by one place. This method throws IndexOutOfBoundsException is the specified index is out of range. If the List implementations doesn’t support this operation, UnsupportedOperationException is thrown.
  2. boolean remove(Object o): This method removes the first occurrence of the specified object. If the list doesn’t contain the given element, it remains unchanged. This method returns true if an element is removed from the list, otherwise false. If the object is null and list doesn’t support null elements, NullPointerException is thrown. UnsupportedOperationException is thrown if the list implementation doesn’t support this method.

List remove() method examples

Let’s look into some examples of remove() methods.

1. Remove element at given index

List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); String removedStr = list.remove(1); System.out.println(list); System.out.println(removedStr);

Output:

[A, B, C, C, B, A] [A, C, C, B, A] B

2. IndexOutOfBoundsException with remove(int index) Method

List<String> list = new ArrayList<>(); list.add("A"); String removedStr = list.remove(10);

Exception Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 10 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.remove(ArrayList.java:535) at com.journaldev.java.ArrayListRemove.main(ArrayListRemove.java:19)

3. Unmodifiable List remove() UnsupportedOperationException Example

List.of() method creates an unmodifiable list, so using remove() method will throw UnsupportedOperationException.

jshell> List<String> list = List.of("a", "b"); list ==> [a, b] jshell> list.remove(1); | Exception java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:72) | at ImmutableCollections$AbstractImmutableList.remove (ImmutableCollections.java:108) | at (#64:1) jshell> list.remove("a"); | Exception java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:72) | at ImmutableCollections$AbstractImmutableCollection.remove (ImmutableCollections.java:79) | at (#65:1) jshell>

Delete ArrayList Java

List remove(index) Example

4. Removing an object from the list

List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); boolean isRemoved = list.remove("C"); System.out.println(list); System.out.println(isRemoved); isRemoved = list.remove("X"); System.out.println(list); System.out.println(isRemoved);

Output:

[A, B, C, C, B, A] [A, B, C, B, A] true [A, B, C, B, A] false

References

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.

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.

Delete ArrayList Java


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<String> 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<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 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.

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)