Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.remove()

Removes a list element by index or by value.

Available since: Java 1.2

Syntax

E remove(int index)
boolean remove(Object o)

Parameters

ParameterTypeDescription
indexintThe position of the element to remove.
oObjectThe element to remove (the first occurrence).

Return value

E | booleanBy index — the removed element; by value — `true` if the element was found.

Examples

Removing by index and by value:

void main() {
    List<String> items = new ArrayList<>(List.of("a", "b", "c", "b"));
    items.remove(0);
    IO.println(items);
    items.remove("b");
    IO.println(items);
}

Output:

[b, c, b]
[c, b]

A trap with a list of numbers: remove(1) removes by index:

void main() {
    List<Integer> nums = new ArrayList<>(List.of(5, 1, 7));
    nums.remove(1);
    IO.println(nums);
    nums.remove(Integer.valueOf(7));
    IO.println(nums);
}

Output:

[5, 7]
[5]

Notes

For a List<Integer> the call remove(1) picks the int version and removes the element at index 1. To remove a value pass an object: remove(Integer.valueOf(1)). Removing by value deletes only the first occurrence; for all matches use removeIf().

See also

Related recipes

In the tutorial

  • Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.

Thanks for reading!

Donate to the site — we work hard for you.