Java LinkedList get() Method
get()The method is in JavaLinkedLista common method provided by the class, used to get the element at the specified position from the linked list.LinkedListis in the Java Collections FrameworkListan implementation class of the interface, which uses a doubly linked list data structure to store elements.
get()The basic syntax of the method is as follows:
E get(int index)
Where:
EIndicates the type of elements in the linked listindexis the position of the element to get (counting from 0)
How the get() Method Works
LinkedListofget()The method gets the element at the specified position by traversing the linked list. SinceLinkedListit is implemented based on a linked list, unlikeArrayListthat, it cannot directly access elements randomly by index.
When callingget(index)the method,LinkedListit will:
- Check whether the index is valid (0 ≤ index < size)
- Start traversing from the head or tail of the linked list (start from the nearer end)
- Move node by node until the node at the specified position is found
- Return the element stored at that node
Usage Examples
Basic Usage
Example
public class LinkedListGetExample {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> fruits = new LinkedList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Durian");
// Use the get() method to retrieve elements
String firstFruit = fruits.get(0); // Get the first element
String thirdFruit = fruits.get(2); // Get the third element
System.out.println(First fruit: + firstFruit); // Output: Apple
System.out.println(Third fruit: + thirdFruit); // Output: Cherry
}
}
Iterating Through a LinkedList
Example
public class LinkedListTraversal {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
// Use the get() method to iterate through the LinkedList
for (int i = 0; i < numbers.size(); i++) {
System.out.println(No. + i + element: + numbers.get(i));
}
}
}
Performance Considerations
LinkedListofget()The time complexity of the method is O(n), because it needs to traverse the linked list from the head or tail to find the element at the specified position. This is in contrast toArrayListthe O(1) time complexity of the latter.
Therefore, if you need frequent random access to elements,ArrayListmay be a better choice. WhileLinkedListperforms better when there are frequent insert and delete operations.
Exception Handling
When using theget()method, if the passed index is out of range (index < 0 or index ≥ size), it will throwIndexOutOfBoundsException。
Safe Usage Example
Example
public class SafeGetExample {
public static void main(String[] args) {
LinkedList<String> colors = new LinkedList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
int index = 3; // Out-of-range index
try {
String color = colors.get(index);
System.out.println(color);
} catch (IndexOutOfBoundsException e) {
System.out.println(Error: Index + index + out of range. List size is + colors.size());
}
}
}
Alternative Methods
Besidesget()the method,LinkedListthe LinkedList class also provides other methods to get elements:
getFirst(): get the first elementgetLast(): get the last elementpeek(): get but do not remove the first element (returns null if the list is empty)peekFirst(): same as peek()peekLast(): get but do not remove the last element (returns null if the list is empty)
Example
Example
public class AlternativeMethods {
public static void main(String[] args) {
LinkedList<String> books = new LinkedList<>();
books.add("Java Programming");
books.add("Data Structures");
books.add("Algorithms");
System.out.println(First book: + books.getFirst());
System.out.println(Last book: + books.getLast());
System.out.println("peek(): " + books.peek());
System.out.println("peekLast(): " + books.peekLast());
}
}
Best Practices
Avoid using the get() method frequently: Since
LinkedListofget()the method has lower performance, if you need frequent random access, consider usingArrayList。Use an iterator to traverse: When you need to traverse
LinkedLista LinkedList, using an iterator is more efficient than usingget()the get() method:
Example
for (String fruit : fruits) {
System.out.println(fruit);
}
// Or use an iterator
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
- Check the index range: Before using
get()the method, it is best to check whether the index is valid:
Example
return list.get(index);
} else {
// Handle invalid index cases
}
Summary
LinkedListofget()The method is a basic but important method; it allows us to access elements in the linked list by index. Although its performance is not as good asArrayListthe corresponding method, in some scenarios (such as frequent insertion and deletion)LinkedListit is still a better choice. Understandingget()how the method works and its performance characteristics can help us make more reasonable data structure choices in actual development.
Java LinkedList