Java LinkedList Class


The LinkedList class found in the java.util package provides a doubly-linked list implementation of the List, Deque, and Queue interfaces in Java. LinkedList enables quicker insertions and deletions than ArrayList which proves beneficial for large lists that require regular changes.


Key Features

  • Each node within a doubly-linked list contains pointers to both the preceding and following nodes.
  • Allows duplicates
  • Maintains insertion order
  • Implements List, Deque, and Queue interfaces
  • Not synchronized (not thread-safe)

Syntax

 LinkedList list = new LinkedList();

Example

LinkedList animals = new LinkedList<>(); 

Example

import java.util.LinkedList;

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

        // Add elements
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // Add first and last
        colors.addFirst("Black");
        colors.addLast("White");

        // Display elements
        for (String color : colors) {
            System.out.println(color);
        }

        // Access and modify
        System.out.println("First: " + colors.getFirst());
        System.out.println("Last: " + colors.getLast());

        // Remove elements
        colors.remove("Green");
        colors.removeFirst();

        // Display final list
        System.out.println("After removal: " + colors);
    }
} 

Note

  • LinkedList is preferred for frequent insertions/deletions.
  • Use ArrayList for random access and iteration.
  • Not thread-safe; use Collections.synchronizedList() if needed.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.