Java Reference Library →

LinkedList get() method - Syntax and Examples

LinkedList get() method - Syntax and Examples

Learn about the Java LinkedList's get() method, including its syntax, parameters, return value, and examples. This guide explains how to retrieve elements from a LinkedList by their index.

This reference explains LinkedList get() method - Syntax and Examples through its syntax, examples and boundaries. Use the linked course lessons when the surrounding Java concepts are unfamiliar.

  1. Use this reference

    Identify the documented behavior, read a complete example and check its inputs before applying it.

LinkedList get() method - Syntax and Examples

Introduction

The get() method in Java's LinkedList is your tool for accessing elements within the list. Unlike ArrayList, which offers direct access through indices (because of its underlying array), LinkedList uses a linked structure. Therefore, retrieving an element by index requires traversing the list from the beginning until you reach the desired position. This makes get() operations potentially slower than in an ArrayList, especially for elements near the end of the list.

Syntax

public E get(int index)

Parameters

Parameter Description
index The index of the element to retrieve. The index starts from 0.

Return Value

The method returns the element at the specified index.

Examples

Example 1: Retrieving an Element

This example demonstrates how to retrieve a specific element from a LinkedList using its index. We'll create a LinkedList of strings, add some elements, and then use the get() method to access one of them.

import java.util.LinkedList;

public class GetExample {
    public static void main(String[] args) {
        LinkedList<String> myList = new LinkedList<>();
        myList.add("Apple");
        myList.add("Banana");
        myList.add("Cherry");

        // Get the element at index 1 (which is "Banana")
        String fruit = myList.get(1);
        System.out.println("Element at index 1: " + fruit);
    }
}
Element at index 1: Banana

In this example, `myList.get(1)` retrieves the element present at the second position (index 1) of the LinkedList, which is “Banana”. This value is then stored in the 'fruit' variable and printed to the console.

Example 2: Handling Index OutOfBoundsException

This example shows what happens when you try to access an element at an index that doesn't exist within your LinkedList. Attempting to get an element beyond the list’s bounds will result in an IndexOutOfBoundsException.

import java.util.LinkedList;

public class GetExample2 {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        try {
            int value = numbers.get(5); // Index 5 is out of bounds
            System.out.println("Value at index 5: " + value);
        } catch (IndexOutOfBoundsException e) {
            System.err.println("Error: IndexOutOfBoundException -  Index is out of range.");
        }
    }
}
Error: IndexOutOfBoundException -  Index is out of range.

Here, we attempt to get the element at index 5. Since the LinkedList only contains three elements (indices 0, 1, and 2), accessing index 5 throws an IndexOutOfBoundsException. The `try-catch` block gracefully handles this exception and prints an error message.

Example 3: Retrieving Elements in a Loop

This example demonstrates how you can use the get() method inside a loop to access all elements of a LinkedList sequentially. Remember that because LinkedLists need to traverse from the beginning for each get, this isn't the most efficient way to iterate through them.

import java.util.LinkedList;

public class GetExample3 {
    public static void main(String[] args) {
        LinkedList<String> colors = new LinkedList<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        for (int i = 0; i < colors.size(); i++) {
            String color = colors.get(i);
            System.out.println("Color at index " + i + ": " + color);
        }
    }
}
Color at index 0: Red
Color at index 1: Green
Color at index 2: Blue

This loop iterates from index 0 to the last element of `colors`. In each iteration, the element at the current index is retrieved using `colors.get(i)` and then printed.

Using this reference

Check the example’s types, inputs and documented behavior before copying it into an application. Some APIs require external libraries, files or platform services; consult their setup notes.

Related explanations: Java Data Types - Primitive and Non-Primitive, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide.

Reference checks are optional and do not count toward course progress.

    Reference library →