Java LinkedList

LinkedList is a doubly-linked list implementation of the List and Deque interfaces in Java. It is part of the java.util package and is useful when frequent insertions and deletions are required.

1. Creating a LinkedList

import java.util.LinkedList;

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

2. Adding Elements

Use add(), addFirst(), and addLast() methods.

list.add("Apple");
list.addFirst("Banana");
list.addLast("Cherry");

3. Accessing Elements

Use get(), getFirst(), and getLast() methods.

String first = list.getFirst();
String last = list.getLast();

4. Iterating Over a LinkedList

for (String item : list) {
    System.out.println(item);
}

5. Common Methods

  • removeFirst() - Removes and returns the first element.
  • removeLast() - Removes and returns the last element.
  • size() - Returns the number of elements.
  • clear() - Removes all elements.

6. ArrayList vs. LinkedList

ArrayList LinkedList
Better for frequent random access. Better for frequent insertions and deletions.
Uses dynamic array. Uses doubly-linked list.

7. Key Takeaways

  • LinkedList is efficient for insertions and deletions.
  • Implements both List and Deque interfaces.
  • Allows duplicate elements and maintains insertion order.
  • Not synchronized; external synchronization is required for thread safety.