LinkedList:
- A LinkedList in Java is a doubly linked list implementation of the List and Deque interfaces, best when you need fast insertions and deletions but not random access.
- A LinkedList is a linear data structure that stores elements in nodes, where each node contains:
- The data (element)
- A reference (pointer) to the next node
- A reference (pointer) to the previous node (in case of doubly linked list)
Key Points:
- Part of Java Collections Framework -> Defined in java.util package.
- Implements List, Deque, Queue interfaces.
- Dynamic size -> Unlike arrays, it can grow or shrink dynamically.
- Allows duplicates & null -> Unlike Set, it allows duplicate elements and multiple null values.
- Not synchronized -> Multiple threads can cause issues if not handled properly. Use Collections.synchronizedList() if needed.
Common Methods:
- add(E e), addFirst(E e), addLast(E e) → Add elements
- remove(), removeFirst(), removeLast() → Remove elements
- get(int index), getFirst(), getLast() → Access elements
- contains(Object o) → Check if element exists
- size() → Number of elements
- clear() → Remove all elements
Advantages:
- Efficient insertion & deletion (O(1) if position known).
- Can be used as a List, Queue, or Deque.
Disadvantages:
- Accessing an element by index is slower (O(n)) compared to ArrayList’s O(1).
- More memory usage (because of storing next & prev references).
Top comments (0)