LinkedList
is a part of the Java Collections Framework and provides a doubly-linked list implementation of the List
and Deque
interfaces. It is ideal for frequent insertions and deletions, especially in the middle of the list.
📚 What is LinkedList?
A LinkedList
stores elements in nodes, where each node holds data and pointers to the next and previous nodes.
Key Characteristics:
- Maintains insertion order
- Allows
null
and duplicates - Slower access (
O(n)
) but faster insertion/removal (O(1)
for head/tail) - Implements both
List
andDeque
List<String> list = new LinkedList<>();
list.add("One");
list.add("Two");
System.out.println(list.get(1)); // Two
🛠️ Internal Working of LinkedList
Node Structure
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
}
Key Operations:
- Add: Creates a new node and adjusts pointers
- Remove: Updates surrounding nodes’ pointers
- Traversal: Starts from head or tail and follows next/prev links
Memory Usage
Higher than ArrayList
due to object overhead and pointer storage.
⏱️ Performance Benchmarks
Operation | Time Complexity |
---|---|
add(E e) |
O(1) |
get(int index) |
O(n) |
remove(int index) |
O(n) |
addFirst() /removeFirst() |
O(1) |
contains(Object o) |
O(n) |
🧪 Real-World Use Cases
- Queue/Stack operations (
addFirst()
,removeLast()
) - Undo/Redo functionality (linked nodes of states)
- Frequent insertions/removals in the middle of a list
Deque<String> queue = new LinkedList<>();
queue.add("A");
queue.add("B");
queue.remove(); // A
🔁 LinkedList vs ArrayList
Feature | LinkedList | ArrayList |
---|---|---|
Access | Slow (O(n)) | Fast (O(1)) |
Insertion/Removal | Fast (O(1) at head/tail) | Slow (O(n)) |
Memory | High | Low |
Use Case | Insert/delete heavy | Access heavy |
Random Access | No | Yes |
🧬 Java Syntax and Stream Usage
List<String> data = new LinkedList<>();
data.add("java");
data.add("spring");
List<String> upper = data.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
❌ Common Misuses and Anti-Patterns
❌ Using LinkedList for random access
String item = list.get(999); // Very slow
✅ Use ArrayList
instead if random access is needed frequently.
❌ Using LinkedList in multithreaded code without sync
List<String> unsafe = new LinkedList<>(); // Not thread-safe
✅ Use Collections.synchronizedList()
or ConcurrentLinkedDeque
✅ Best Practices
- Use when insertions/removals dominate
- Avoid using
.get(index)
repeatedly in loops - Wrap in
Collections.synchronizedList()
for thread safety - Use
Deque
methods (addFirst
,removeLast
) for queue operations
📌 What's New in Java Versions?
Java 8
forEach()
,removeIf()
, streams and lambdas support
Java 9
List.of(...)
creates immutable lists (not LinkedList)
Java 10
var
for local variables
Java 11
- Improved memory efficiency
Java 17
- Pattern matching improvements
Java 21
- Performance boosts, structured concurrency enhancements
🔁 Refactoring Example
Before (inefficient):
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
After (efficient):
for (String item : list) {
System.out.println(item);
}
🧠 Real-World Analogy
Think of a LinkedList like a chain of people holding hands. You can easily add or remove someone in the middle without shifting everyone, but finding a specific person takes time.
❓ FAQ: Expert-Level Questions
-
Is LinkedList synchronized?
- No, it’s not thread-safe.
-
Does it support
null
values?- Yes, any number of
null
s.
- Yes, any number of
-
How does
remove()
work internally?- Adjusts
prev
andnext
pointers to exclude the node.
- Adjusts
-
How to implement a stack using LinkedList?
Deque<Integer> stack = new LinkedList<>(); stack.push(10); stack.pop();
-
How is it different from Deque?
LinkedList
implementsDeque
.
-
Does LinkedList support fail-fast iterators?
- Yes, it throws
ConcurrentModificationException
.
- Yes, it throws
-
Is memory overhead significant?
- Yes, due to node objects and links.
-
Can LinkedList be used in sorting?
- Yes, but sorting is slower compared to arrays.
-
What interface does it implement?
List
,Deque
,Queue
-
How to convert LinkedList to ArrayList?
List<String> arrayList = new ArrayList<>(linkedList);
🏁 Conclusion and Key Takeaways
LinkedList
is a powerful tool for insert/remove-heavy use cases.- It trades off access speed for modification speed.
- Combining with
Deque
,Stream
, and Java 8+ APIs unlocks its full potential. - Avoid misuse in random-access or concurrent scenarios without proper handling.
💡 Pro Tip: When in doubt, default to
ArrayList
. Reach forLinkedList
only when its strengths match your use case.