Exploring Java's Built-in LinkedList

Introduction

Hello! Sometimes, you don't have to implement the linked list yourself. Java has a built-in LinkedList class — a fundamental tool for implementing data structures. We have even used it a bit for initializing queues and stacks. In this lesson, you will learn to use Java's LinkedList, understand its methods, and see them in action.

Overview of Java's LinkedList

Java's LinkedList is part of the Java Collections Framework. It represents a doubly-linked list and provides numerous methods for performing operations like adding and removing elements, searching elements, and iterating through the list.

A doubly-linked list is similar to a singly-linked list, but with one key difference. While a singly-linked list has nodes containing a reference to the next node in the sequence, in a doubly-linked list, each node contains a reference to both the next node and the previous node in the sequence. This gives more flexibility in navigating through the list, allowing both forward and backward traversals, but at the cost of increased complexity and resource usage for maintaining references in both directions.

Working with Java's LinkedList

Let’s begin by creating a LinkedList in Java. You start by instantiating the LinkedList class, as shown below:

import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList<String> students = new LinkedList<>();
  }
}

In the above code, we create a LinkedList called students that will store String type data. However, it's currently empty. Let's see how we can operate on this LinkedList.

Methods in LinkedList

Java's LinkedList class comes loaded with many powerful methods. We'll focus on some basic yet very important ones:

  • add(E element): This method appends the specified element to the end of the list.
  • add(int index, E element): This method inserts the specified element at the specified position in the list.
  • remove(): This method retrieves and removes the list's head (the first element).
  • get(int index): Returns the element at the specified position in the list.

These methods are demonstrated in the following code:

import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> students = new LinkedList<>();

        students.add("John");
        students.add(0, "Alice");
        System.out.println(students.get(0));  // prints Alice
        students.remove();
        System.out.println(students.get(0));  // prints John
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal