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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.