Java - LinkedList Methods Part 2: Accessing Elements
Accessing elements in a LinkedList is straightforward with methods like get(), getFirst(), and getLast().
Examples and Explanation
Using get()
System.out.println(list.get(2)); // Output: Apple
Explanation: Retrieves the element at the specified index.
Using getFirst()
System.out.println(list.getFirst()); // Output: Cherry
Explanation: Efficiently retrieves the first element, useful for queue operations.
Using getLast()
System.out.println(list.getLast()); // Output: Grape
Explanation: Fetches the last element, useful in stack or deque contexts.
Using a Loop
for (String item : list) {
System.out.print(item + " ");
}
// Output: Cherry Elderberry Apple Banana Date Fig Grape
Explanation: Access elements sequentially for processing or display.
Random Access Example
System.out.println("Middle Element: " + list.get(list.size() / 2)); // Output: Banana
Explanation: Retrieves an element based on calculated index, like the middle element.