Java LinkedList get() Method

Java LinkedList Java LinkedList


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 list
  • indexis 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:

  1. Check whether the index is valid (0 ≤ index < size)
  2. Start traversing from the head or tail of the linked list (start from the nearer end)
  3. Move node by node until the node at the specified position is found
  4. Return the element stored at that node

Usage Examples

Basic Usage

Example

import java.util.LinkedList;

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

import java.util.LinkedList;

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

import java.util.LinkedList;

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:

  1. getFirst(): get the first element
  2. getLast(): get the last element
  3. peek(): get but do not remove the first element (returns null if the list is empty)
  4. peekFirst(): same as peek()
  5. peekLast(): get but do not remove the last element (returns null if the list is empty)

Example

Example

import java.util.LinkedList;

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

  1. Avoid using the get() method frequently: SinceLinkedListofget()the method has lower performance, if you need frequent random access, consider usingArrayList。

  2. Use an iterator to traverse: When you need to traverseLinkedLista LinkedList, using an iterator is more efficient than usingget()the get() method:

Example

// More efficient way to iterate
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());
}
  1. Check the index range: Before usingget()the method, it is best to check whether the index is valid:

Example

if (index >= 0 && index < list.size()) {
    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 Java LinkedList

Other Extensions