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.
- 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 doesnt support this operation, UnsupportedOperationException is thrown.
- boolean remove[Object o]: This method removes the first occurrence of the specified object. If the list doesnt 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 doesnt support null elements, NullPointerException is thrown. UnsupportedOperationException is thrown if the list implementation doesnt support this method.
List remove[] method examples
Lets look into some examples of remove[] methods.
1. Remove element at given index
List 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:
2. IndexOutOfBoundsException with remove[int index] Method
List 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.
List remove[index] Example
4. Removing an object from the list
List 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] falseReferences
- List remove[] API Doc