Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

List.remove(Object): remove the first match

Remove the first occurrence of a value, such as a subscriber name, and use the `boolean` result to tell whether anything was removed. Contrast this with removal by index.

Version: Java SE 21

Syntax

boolean remove(Object o); // remove by value
E remove(int index);      // remove by zero-based index

List.remove(Object) updates the list in place. It removes only the element at the lowest index i for which Objects.equals(o, get(i)) is true. Later matches remain. If the call completes normally, it returns true when it removes an element or false when nothing matches and the list stays unchanged. In unsubscribe, the String argument is a name, not a position.

The remove(int index) overload removes the element at a zero-based index, returns that element as type E, and throws IndexOutOfBoundsException for an invalid index. With a List<Integer>, numbers.remove(1) removes the element at index 1, while numbers.remove(Integer.valueOf(7)) removes the first value 7. The compiler resolves the overload using the argument type, not the expected return type: a match that needs no boxing or unboxing takes priority.

Removal is optional. ArrayList supports it, but a list returned by List.of(...) throws UnsupportedOperationException even when there is no match. Depending on the implementation, removal by value can also throw ClassCastException for an incompatible type or NullPointerException for null if the list does not allow null.

Examples

import java.util.ArrayList;
import java.util.List;

public class Main {
    static boolean unsubscribe(List<String> names, String name) {
        return names.remove(name);
    }

    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Ada", "Lin", "Ada"));
        System.out.println(unsubscribe(names, "Ada"));
        System.out.println(names);
        System.out.println(unsubscribe(names, "Sam"));
        System.out.println(names);

        List<Integer> numbers = new ArrayList<>(List.of(7, 9, 7));
        System.out.println(numbers.remove(1));
        System.out.println(numbers.remove(Integer.valueOf(7)));
        System.out.println(numbers);
    }
}

Result

true
[Lin, Ada]
false
[Lin, Ada]
9
true
[7]

Each `new ArrayList<>(List.of(...))` makes a mutable copy. The first `Ada` is removed, the second remains, and the missing `Sam` gives `false`. In the number list, `9` at index `1` is removed first, followed by the first value `7`.

Related lessons

  • Java · Lesson 22 · Intermediate · Version: 2
  • Java · Lesson 26 · Intermediate · Version: 2

Sources