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
| Parameter | Type | Description |
|---|---|---|
| index | int | The position of the element to remove. |
| o | Object | The 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
- List.add() — Adds an element to the end of a list or at a given position.
- Collection.removeIf() — Removes all collection elements that match a condition.
- List.indexOf() — Finds the position of an element in a list.
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.