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.
remove()
MethodsThere are two remove()
methods to remove elements from the List.
E remove(int index)
: This method removes the element at the specified index and returns it. The subsequent elements are shifted to the left by one place. This method throws IndexOutOfBoundsException
if the specified index is out of range. If the list implementations does not support this operation, UnsupportedOperationException
is thrown.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.Let’s look into some examples of remove()
methods.
This example will explore E remove(int index)
:
First, this code constructs and prints a list:
Then, this code executes remove(1)
to remove the element at index 1
. Finally, it prints the new resulting list and also prints the removed element.
The B
at index 1
has been removed.
IndexOutOfBoundsException
with remove(int index)
MethodThis example will explore E remove(int index)
when the index exceeds the list:
This code constructs a list with a length of 1
. However, when the code attempts to remove the element at index 10
:
This attempt throws the IndexOutOfBoundsException
.
remove()
UnsupportedOperationException
ExampleThe List.of()
method creates an immutable list, which can’t be modified.
First, this code constructs and prints an immutable list:
Then the code attempts to use the remove()
method to remove the element at index 1
:
This attempt throws UnsupportedOperationException
. It will also throw UnsupportedOperationException
if you attempt list.remove("a")
or list.remove("b")
.
This example will explore boolean remove(Object o)
:
First, this code constructs and prints a list:
Then, this code executes remove("C")
to remove the first instance of C
. Next, it prints the resulting list and also prints the boolean value of the operation - true
:
Then, this code executes remove("X")
, but there is no instance of X
in the list, the list does not change. Finally, it prints the list and also prints the boolean value of the operation - false
:
In many applications, you might need to remove specific elements from a list based on certain conditions. For example, in a social media platform, you might want to remove all posts from a user who has been banned. You can use the remove()
method to achieve this. Here’s an example:
When processing data in web or backend applications, you might need to filter out certain elements from a list based on specific criteria. The remove()
method can be used to clean up the list after filtering. For instance, in an e-commerce platform, you might want to remove all products that are out of stock from a list of products to be displayed to customers. Here’s an example:
Before processing data, it’s essential to ensure that the data is clean and free of duplicates. The remove()
method can be used to remove duplicates from a list. For example, in a data processing pipeline, you might want to remove duplicate records from a list of data entries. Here’s an example:
ConcurrentModificationException
when removing inside a for-each loopA ConcurrentModificationException
occurs when you try to modify a list (e.g., by removing an element) while iterating over it using a for-each loop. This is because the for-each loop is designed to iterate over the list in its original state, and modifying the list during iteration can lead to unpredictable behavior.
To fix this error, you can use an iterator explicitly and call its remove()
method to safely remove elements from the list while iterating. Here’s an example:
Alternatively, you can use a traditional for loop with an index and remove elements using the remove(int)
method. However, be careful when adjusting the index to account for the removed elements.
remove(int)
and remove(Object)
in overloaded methodsThe remove(int)
method removes the element at the specified index, while the remove(Object)
method removes the first occurrence of the specified element. If the element is not found in the list, the remove(Object)
method does not modify the list and returns false
.
To avoid confusion between these methods, ensure you understand the context and the type of parameter you are passing. If you need to remove an element by its index, use remove(int)
. If you need to remove an element by its value, use remove(Object)
.
Here is a comparison table to help you understand the differences:
Method | Parameter Type | Description | Returns |
---|---|---|---|
remove(int) |
int |
Removes the element at the specified index. | The element that was removed from the list. |
remove(Object) |
Object |
Removes the first occurrence of the specified element. | true if the list contained the specified element, false otherwise. |
Remember to use the correct method based on your requirements to avoid unexpected behavior or errors.
IndexOutOfBoundsException
errorAn IndexOutOfBoundsException
occurs when you try to access or remove an element at an index that is out of the list’s bounds. This can happen if you pass an index that is less than 0 or greater than or equal to the list’s size.
To fix this error, ensure that the index you are using is within the valid range of the list. You can do this by checking the list’s size before attempting to access or remove an element. Here’s an example:
remove()
vs removeIf()
The remove()
method is used to remove an element from the list based on its index. The removeIf()
method is used to remove elements from the list based on a condition.
Here is a comparison table to help you understand the differences:
Method | Description | Returns | Throws |
---|---|---|---|
remove(int) |
Removes the element at the specified index. | The element that was removed from the list. | IndexOutOfBoundsException if the index is out of range (index < 0 or index >= size()). |
remove(Object) |
Removes the first occurrence of the specified element. | true if the list contained the specified element, false otherwise. |
None |
removeIf(Predicate<? super E> filter) |
Removes all elements of the list that match the given predicate. | true if any elements were removed, false otherwise. |
UnsupportedOperationException if the list implementation does not support this operation. |
The remove(int)
method removes the element at the specified index, while the remove(Object)
method removes the first occurrence of the specified element. Here’s an example:
You can use the clear()
method to remove all elements from a list. Here’s an example:
remove()
inside a loop?Yes, you can use remove()
inside a loop, but be careful when adjusting the index to account for the removed elements. Here’s an example:
ConcurrentModificationException
when removing?To avoid ConcurrentModificationException
, use an Iterator
to iterate over the list and remove elements. Here’s an example:
You can use the remove(Object)
method to remove an element by its value. Here’s an example:
remove()
not work on some lists in Java 9+?In Java 9+, some lists, such as List.of()
, are immutable and do not support the remove()
method. Attempting to use remove()
on these lists will throw an UnsupportedOperationException
. Here’s an example:
The best way to remove elements conditionally is to use the removeIf()
method, which was introduced in Java 8. Here’s an example:
In this article, you learned about Java’s List
method remove()
, which allows you to remove elements from a list by their index or by their value. You also discovered how to use the removeIf()
method to conditionally remove elements based on a predicate. Additionally, you were introduced to the concept of immutable lists in Java 9+, which do not support the remove()
method. By mastering these techniques, you can effectively manage and manipulate lists in your Java applications.
Recommended Reading:
References:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Thanks for this post…it helps.
- Possible
why gives me a compile error which it tell cannot find the symbol
- Danuja