get()
Reads the element at a zero-based index, with the bounds rules and the LinkedList cost that catch people out.
E get(int index)- Added in Java Java 1.2
Parameters
| Parameter | Type | Description |
|---|---|---|
$index | int | Zero-based position, from 0 to size() - 1. |
Return value
EThe element stored at the given position. It may be null if the list allows null elements.
Errors
IndexOutOfBoundsException if index < 0 or index >= size(). Lists from List.of may throw the ArrayIndexOutOfBoundsException subclass.
get(index) returns the element at a position. Indexes start at 0, so the last element is at size() - 1. It does not remove anything and does not change the list.
Bounds
Any index below 0 or at size() or above throws IndexOutOfBoundsException. The common bugs are get(list.size()) in a hand-written loop and get(0) on a list that turned out to be empty, for example a database query that matched no rows. Check isEmpty() first, or use getFirst() (Java 21), which throws the clearer NoSuchElementException.
On ArrayList the message reads Index 2 out of bounds for length 2. That text shows up in logs as a 500 error, so it pays to validate client-supplied positions and return a 400 or 404 yourself.
Cost depends on the implementation
ArrayList and the lists from List.of implement the marker interface RandomAccess: get is constant time. LinkedList does not. Its get walks the nodes from the nearer end, so a classic for (int i = 0; i < list.size(); i++) list.get(i) loop over a LinkedList is quadratic. A for-each loop uses the iterator and is linear for every list, which is one reason to prefer it.
When not to use get
- Looping over every element: use for-each or a stream.
- Looking something up by id: a
Mapkeyed by id is constant time, while scanning a list is linear. - Reading the first or last element:
getFirst()andgetLast()say what you mean.
get is the right tool when position carries meaning: a column in a parsed CSV line, the nth result a client asked for, or a slot in a fixed-size table.
Example
When to use it
- Reading fields by column position from a parsed CSV or fixed-width import line.
- Returning the nth item of a ranked search result that a client asked for.
- Reading parameters from a fixed-shape array in a JSON request body after parsing.
Frequently asked questions
How do I get the last element of a list in Java?
Use list.getLast() on Java 21 and later, or list.get(list.size() - 1) on older versions. Both fail on an empty list, so check isEmpty() first.
Is ArrayList.get O(1)?
Yes. ArrayList stores elements in an array, so get is constant time. LinkedList.get is linear because it walks the nodes, which makes indexed loops over a LinkedList slow.
More examples
Reading CSV fields by position
Position is the meaning of each field, so get is the natural call. Checking size before reading an optional trailing column avoids an exception on short lines.
void main() {
String line = "42,[email protected]";
List<String> fields = List.of(line.split(","));
int id = Integer.parseInt(fields.get(0));
String email = fields.get(1);
String role = fields.size() > 2 ? fields.get(2) : "user";
IO.println(id + " " + email + " " + role);
}
// Output:
// 42 [email protected] userA safe lookup that returns Optional
Checking the bounds once in a helper keeps an out-of-range position from a query string from turning into a 500 error.
<T> Optional<T> at(List<T> list, int index) {
if (index < 0 || index >= list.size()) {
return Optional.empty();
}
return Optional.ofNullable(list.get(index));
}
void main() {
List<String> results = List.of("first", "second");
IO.println(at(results, 1).orElse("none"));
IO.println(at(results, 5).orElse("none"));
IO.println(at(results, -1).orElse("none"));
}
// Output:
// second
// none
// noneWhich lists have fast get
RandomAccess marks lists where get is constant time. For a LinkedList, the for-each loop visits each node once instead of walking from the start for every index.
void main() {
List<String> array = new ArrayList<>(List.of("a", "b", "c"));
List<String> linked = new LinkedList<>(array);
IO.println("ArrayList RandomAccess: " + (array instanceof RandomAccess));
IO.println("LinkedList RandomAccess: " + (linked instanceof RandomAccess));
StringBuilder out = new StringBuilder();
for (String s : linked) {
out.append(s);
}
IO.println(out);
}
// Output:
// ArrayList RandomAccess: true
// LinkedList RandomAccess: false
// abc
Discussion