In Java, get(index) returns the element stored at a position in the LinkedList. Positions start at 0, so the first element is at index 0 and the last one is at size() - 1.
The element stays in the list. Unlike an ArrayList, a LinkedList has no array to jump into: Java must walk the chain of nodes to reach the position, starting from whichever end is closer.
An instance method of java.util.LinkedList (since Java 1.2): call it on a LinkedList object. Add import java.util.LinkedList; at the top of your file. It is declared by List, and LinkedList implements it.
Syntax
Pass a valid index.
Java
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
String first = list.get(0); // "A"
String last = list.get(list.size() - 1); // "C"
Call
What it does
list.get(i)
Returns the element at index i. The list is not changed.
list.getFirst()
Returns the first element, with no index.
list.getLast()
Returns the last element, with no index.
list.set(i, e)
Replaces the element at i instead of reading it.
The cost of get(i) grows with the distance from the nearest end. Reaching the middle of a long list is the slowest case.
Library declarations
Java
// java.util.LinkedList
public E get(int index)
Parameters
Parameter
Description
index (int)
The position to read, from 0 to size() - 1.
Return Value
Return Value
Description
E
The element at that index. It can be null if a null was stored there.
last valid: A3
get(3) -> IndexOutOfBoundsException
get(-1) -> IndexOutOfBoundsException
How It Works
Three seats. The valid indexes are 0, 1 and 2.
Index 2 works. It is the last position, and returns A3.
Index 3 is one too many. An index equal to size() points past the end, so Java throws IndexOutOfBoundsException.
Negative indexes fail too. There is no counting from the end in Java, so get(-1) throws the same exception.
Frequently Asked Questions
Call list.get(index). The first element is at index 0 and the last is at size() - 1.
It can be. A LinkedList has to walk its chain of nodes to reach the index, so the time grows with the position. An ArrayList reaches any index instantly.
get throws an IndexOutOfBoundsException when the index is negative or equal to or larger than size().
No. It only reads the element. Use remove(index) to read and delete it in one step.
Use a for-each loop or an iterator. They visit each node once, while get(i) in a loop repeats the walk for every index.