Java LinkedList

Introduction

The Java LinkedList class is one of the most important implementations of the List interface in the Java Collection Framework. Unlike ArrayList, which stores elements in a dynamic array, LinkedList stores elements as a doubly linked list. This structure makes insertion and deletion operations much faster, especially when working with elements in the middle or at the beginning of the collection.

The LinkedList class belongs to the java.util package and implements both the List and Deque interfaces. Because of this, it can be used not only as a list but also as a queue, deque, and stack.

LinkedList is widely used in applications where data changes frequently, such as browser history, music playlists, undo/redo operations, task scheduling, and queue management.

What is Java LinkedList?

LinkedList is a class in the Java Collection Framework that implements the List and Deque interfaces. It stores elements as a doubly linked list, where each node contains:

  • The data (element)
  • A reference to the previous node
  • A reference to the next node

Unlike arrays, the elements are not stored in contiguous memory locations.

Key Characteristics

  • Implements List and Deque interfaces
  • Maintains insertion order
  • Allows duplicate elements
  • Allows multiple null values
  • Dynamic size
  • Fast insertion and deletion
  • Slower random access
  • Not synchronized

Java LinkedList Hierarchy


Object
   │
AbstractCollection
   │
AbstractList
   │
AbstractSequentialList
   │
LinkedList

Interfaces Implemented

  • List
  • Deque
  • Queue
  • Cloneable
  • Serializable

Features of Java LinkedList

Some important features include:

  • Dynamic size
  • Doubly linked list implementation
  • Fast insertion and deletion
  • Maintains insertion order
  • Allows duplicate values
  • Allows null elements
  • Can work as a List, Queue, Deque, and Stack
  • Supports Generics
  • Provides bidirectional traversal

Syntax

Import Statement


import java.util.LinkedList;
or
import java.util.*;

Creating a LinkedList


ArrayList<String> list = new ArrayList<>();

Using the List interface:


List<String> fruits = new LinkedList<>();

Using the Queue interface:


List<String> queue = new LinkedList<>();

Using the Deque interface:


List<String> deque = new LinkedList<>();

Constructors of LinkedList

1. Default Constructor


ArrayList<String> list = new ArrayList<>();

Creates an empty LinkedList.

2. Constructor Using Another Collection


ArrayList<String> language= new ArrayList<>();
languages.add("Java");
languages.add("Python");
ArrayList<String> list = new linked list<>();

Creates a LinkedList containing all elements from another collection.

Common Methods of LinkedList

Method Description
add() Adds an element
addFirst() Adds an element at the beginning
addLast() Adds an element at the end
get() Returns an element by index
getFirst() Returns the first element
getLast() Returns the last element
remove() Removes an element
removeFirst() Removes the first element
removeLast() Removes the last element
set() Updates an element
size() Returns the number of elements
contains() Checks whether an element exists
clear() Removes all elements
peek() Returns the first element without removing it
poll() Returns and removes the first element

Example 1: Creating a LinkedList


import java.util.*;

public class LinkedListExample {

    public static void main(String[] args) {

     ArrayList<String> fruit = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        System.out.println(fruits);
    }
}

Output

[Apple, Banana, Mango]

Example 2: Adding First and Last Elements


import java.util.*;

public class AddExample {

    public static void main(String[] args) {

  ArrayList<String> city = new ArrayList<>();

        cities.add("Delhi");
        cities.add("Mumbai");

        cities.addFirst("Jaipur");
        cities.addLast("Pune");

        System.out.println(cities);
    }
}

Output

[Jaipur, Delhi, Mumbai, Pune]

Example 3: Accessing First and Last Elements


import java.util.*;

public class GetExample {

    public static void main(String[] args) {

     ArrayList<String> list = new ArrayList<>();

        list.add("Java");
        list.add("Python");
        list.add("C++");

        System.out.println(list.getFirst());
        System.out.println(list.getLast());
    }
}

Output

Java
C++

Example 4: Removing Elements


import java.util.*;

public class RemoveExample {

    public static void main(String[] args) {

          ArrayList<String> number = new ArrayList<>();

        numbers.add("One");
        numbers.add("Two");
        numbers.add("Three");

        numbers.removeFirst();
        numbers.removeLast();

        System.out.println(numbers);
    }
}

Output

Java
Python
Spring Boot

LinkedList vs ArrayList

Feature ArrayList LinkedList
Internal Structure Dynamic Array Doubly Linked List
PRandom Access Fast Slow
Insertion/Deletion Slower in middle Faster
Memory Usage Less More
Best For Frequent reads Frequent insertions/deletions

Time Complexity

Operation Time Complexity
Add (End) O(1) (Amortized)
Add (Middle) O(n)
get() O(1)
Set O(1)
Remove (End) O(1)
Remove (Middle) O(n)
Search O(n)

Finding the node requires traversal, but once located, insertion or deletion is efficient because only links need to be updated.

Real-life Example

Imagine you’re developing a browser application.

Every time a user visits a webpage:

  • The page is added to the browsing history.
  • Clicking the Back button moves to the previous page.
  • Clicking the Forward button returns to the next page.

A LinkedList is well-suited for this because inserting and removing pages from the beginning or end is efficient.

Another common example is a music playlist where users frequently add, remove, or rearrange songs.

Other practical applications include:

  • Undo/Redo functionality
  • Train coach management
  • Queue management systems
  • Call center waiting queues
  • Navigation systems

Advantages of LinkedList

  • Dynamic size
  • Fast insertion and deletion
  • Maintains insertion order
  • Allows duplicate values
  • Supports Queue and Deque operations
  • No need to shift elements after insertion or deletion
  • Easy implementation of stacks and queues
  • Supports bidirectional traversal

Limitations of LinkedList

  • Slower random access
  • Higher memory consumption due to node references
  • Searching is slower than in ArrayList
  • Not synchronized
  • Cache performance is generally lower than ArrayList because elements are not stored contiguously

Common Mistakes

1. Using LinkedList for Frequent Random Access

Incorrect choice if your application mostly retrieves elements by index.

Use ArrayList instead.

2. Forgetting Generics

Incorrect:


LinkedList list = new LinkedList();

Correct:


ArrayList<String> list = new ArrayList<>();

3. Accessing Invalid Index


list.get(10);

Throws:


IndexOutOfBoundsException

4. Assuming LinkedList is Thread-Safe

LinkedList is not synchronized.

Use appropriate synchronization if multiple threads modify the list concurrently.

5. Using get() Repeatedly Inside a Loop


for(int i=0;i<list.size();i++){
    System.out.println(list.get(i));
}

Since get(i) is O(n), this can lead to poor performance. Prefer using an enhanced for loop or an Iterator.

Best Practices

  • Declare variables using the List interface:

ArrayList<String> list = new ArrayList<>();
  • Use Generics for type safety.
  • Choose LinkedList when insertions and deletions are frequent.
  • Use ArrayList when random access is more important.
  • Prefer enhanced for loops or iterators for traversal.
  • Use Deque methods (addFirst, addLast, removeFirst, removeLast) when implementing queues or stacks.

Conclusion

The Java LinkedList class is a powerful and flexible implementation of the Java Collection Framework that excels in applications requiring frequent insertions and deletions. Its doubly linked list structure enables efficient modifications at both ends of the collection while maintaining insertion order and allowing duplicate elements.

Although LinkedList is slower than ArrayList for random access, it is an excellent choice for implementing queues, deques, stacks, browser history, playlists, and other dynamic data structures.

Java LinkedList – Interview Questions

Q 1: What is LinkedList in Java?
Ans: A doubly linked list implementation of List and Deque interfaces.
Q 2: Does LinkedList allow duplicate elements?
Ans: Yes, it allows duplicates.
Q 3: Which operations are faster in LinkedList?
Ans: Insertion and deletion.
Q 4: Is LinkedList synchronized?
Ans: No, it is not synchronized.
Q 5: When should LinkedList be used?
Ans: When frequent insertions and deletions are required.

Java Linked List – Objective Questions (MCQs)

Q1. Which package contains the LinkedList class in Java?






Q2. Which of the following is true about a LinkedList in Java?






Q3. Which method is used to add an element at the end of a LinkedList?






Q4. What is the difference between ArrayList and LinkedList?






Q5. Which method is used to remove the first element of a LinkedList?