Java List remove() Methods - ArrayList remove() With Examples

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

Output:

2. IndexOutOfBoundsException with remove(int index) Method

Exception Output:

3. Unmodifiable List remove() UnsupportedOperationException Example

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

4. Removing an object from the list

Output:

References

By admin

Leave a Reply