Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.get()

Returns the list element at an index.

Available since: Java 1.2

Syntax

E get(int index)

Parameters

ParameterTypeDescription
indexintThe 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
Wed

An 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 3

Notes

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

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.