List.get()
Returns the list element at an index.
Available since: Java 1.2
Syntax
E get(int index)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | int | The element position, starting from `0`. |
Return value
EThe element at the given position.
Examples
The first and the last element:
void main() {
List<String> days = List.of("Mon", "Tue", "Wed");
IO.println(days.get(0));
IO.println(days.get(days.size() - 1));
}Output:
Mon
WedAn index outside the list:
void main() {
List<String> days = List.of("Mon", "Tue", "Wed");
try {
days.get(3);
} catch (IndexOutOfBoundsException e) {
IO.println(e.getMessage());
}
}Output:
Index 3 out of bounds for length 3Notes
Valid indexes are from 0 to size() - 1, otherwise IndexOutOfBoundsException is thrown. On an ArrayList it is instant, on a LinkedList it walks the chain. For the first and the last element Java 21 adds getFirst() and getLast().
See also
- List.set() — Replaces the list element at an index.
- List.getFirst() — Returns the first or the last element of an ordered collection.
- List.indexOf() — Finds the position of an element in a list.
- IndexOutOfBoundsException — Thrown when a list or a string is accessed at an index outside the valid range.
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.