Deque & List Implementations
ArrayList vs LinkedList, ArrayDeque, Stack replacement, and performance trade-offs
- Compare ArrayList random access O(1) vs LinkedList node traversal O(n)
- Use ArrayDeque as a stack and queue replacement
- Identify when to choose each List and Deque implementation
Deque, ArrayDeque, List, ArrayList, LinkedList, Vector, and Stack — including time complexities, thread safety, and the ListIterator.Table of Contents
- The
DequeInterface — Double Ended Queue - Deque Method Reference — Complete Table
- Using Deque as a Stack
- ArrayDeque — Concrete Implementation
- ArrayDeque Time Complexity & Thread Safety
- The
ListInterface - List Methods — Complete Reference
- The
ListIterator - ArrayList — Concrete Implementation
- ArrayList Time Complexity & Thread Safety
- LinkedList — Concrete Implementation
- LinkedList Time Complexity & Thread Safety
- Vector — Thread-Safe List
- Stack — Thread-Safe LIFO
- Comparison Table — All Implementations
- Interview Notes
- Summary & Quick Revision
- Practice Questions
1. The `Deque` Interface Double Ended Queue
Overview
Deque (pronounced "deck") stands for Double Ended Queue. It is an interface in the JCF that extends the Queue interface, adding the ability to insert and remove elements from both ends of the queue.
Position in the Hierarchy
Regular Queue vs. Deque
| Operation | Regular Queue | Deque |
|---|---|---|
| Add element | Back only | Front or Back |
| Remove element | Front only | Front or Back |
| Examine element | Front only | Front or Back |
Definition
A Deque is a linear collection that supports element insertion and removal at both ends. It inherits all methods fromQueueand adds symmetric equivalents for the other end.
Real-world Analogy
Think of a double-ended train — passengers can board and exit from either the front or the rear of the train, unlike a regular queue at a ticket counter where everyone enters at the back and exits at the front.
2. Deque Method Reference Complete Table
Deque inherits all Queue methods and adds 12 new ones (4 for insert, 4 for remove, 4 for examine).
Inherited Queue Methods (Still Available in Deque)
| Method | Behavior on Failure | Description |
|---|---|---|
add(e) | Throws exception | Internally calls addLast(e) |
offer(e) | Returns false | Internally calls offerLast(e) |
remove() | Throws exception | Internally calls removeFirst() |
poll() | Returns null | Internally calls pollFirst() |
element() | Throws exception | Internally calls getFirst() |
peek() | Returns null | Internally calls peekFirst() |
Queue methods on a Deque, they automatically delegate to the corresponding First/Last variants shown above. This means a Deque used with only the inherited Queue methods behaves exactly like a normal FIFO queue.New Deque Methods Insert
| Method | End | Behavior on Failure | Description |
|---|---|---|---|
addFirst(e) | Front | Throws exception | Inserts at the start of the deque |
offerFirst(e) | Front | Returns false | Inserts at the start; returns true/false |
addLast(e) | Back | Throws exception | Inserts at the end of the deque |
offerLast(e) | Back | Returns false | Inserts at the end; returns true/false |
New Deque Methods Remove
| Method | End | Behavior on Failure | Description |
|---|---|---|---|
removeFirst() | Front | Throws exception | Removes and returns the first element |
pollFirst() | Front | Returns null | Removes and returns the first element |
removeLast() | Back | Throws exception | Removes and returns the last element |
pollLast() | Back | Returns null | Removes and returns the last element |
New Deque Methods Examine (No Removal)
| Method | End | Behavior on Failure | Description |
|---|---|---|---|
getFirst() | Front | Throws exception | Returns but does NOT remove the first element |
peekFirst() | Front | Returns null | Returns but does NOT remove the first element |
getLast() | Back | Throws exception | Returns but does NOT remove the last element |
peekLast() | Back | Returns null | Returns but does NOT remove the last element |
add/remove/get prefix → throw an exception on failure
- Methods with offer/poll/peek prefix → return false or null on failure3. Using Deque as a Stack
Why Deque Can Model a Stack
A stack follows LIFO (Last In, First Out): elements are added and removed from the same end (the "top").
Since Deque lets you add and remove from both ends independently, you can simulate a stack by always using the same end (front) for both insertions and removals.
Stack Behavior via Deque Methods
Dedicated Stack Methods on Deque
Deque provides two convenience methods that internally call the front-end operations:
| Deque Method | Internally Calls | Stack Equivalent |
|---|---|---|
push(e) | addFirst(e) | Push onto stack |
pop() | removeFirst() | Pop from stack |
Code Example Deque as a Stack
1import java.util.ArrayDeque;2import java.util.Deque;3
4public class DequeAsStack {5 public static void main(String[] args) {6 Deque<Integer> stack = new ArrayDeque<>();7
8 // Push elements (addFirst internally)9 stack.push(1); // [1]10 stack.push(2); // [2, 1]11 stack.push(3); // [3, 2, 1]12 stack.push(4); // [4, 3, 2, 1]13 stack.push(5); // [5, 4, 3, 2, 1]14
15 // Pop elements (removeFirst internally) — LIFO order16 System.out.println(stack.pop()); // 517 System.out.println(stack.pop()); // 418 System.out.println(stack.pop()); // 319 System.out.println(stack.pop()); // 220 System.out.println(stack.pop()); // 121 }22}Output
1524334251ArrayDeque instead of Stack for stack operations, because Stack extends the legacy Vector class (which uses synchronization even in single-threaded contexts), making it slower.4. ArrayDeque Concrete Implementation
Overview
ArrayDeque is a concrete class that implements the Deque interface. It uses a resizable array internally. It is the most commonly used implementation of Deque.
Key Characteristics
- Implements
Deque(and thereforeQueueandCollection) - Backed by a circular resizable array
- Initial capacity: 8 elements (default)
- Capacity doubles when full
- Not thread-safe
- Does NOT allow
nullelements - Maintains insertion order
- Allows duplicate elements
Internal Structure Circular Array
ArrayDeque uses a circular array (also called a ring buffer). It maintains a head pointer and a tail pointer. Elements are added at the tail and removed from the head (for queue mode), or both operations happen at either end.
1Initial (empty):2[ _, _, _, _, _, _, _, _ ] capacity = 83 ↑head=0, tail=04
5After addLast(1), addLast(2), addLast(3):6[ 1, 2, 3, _, _, _, _, _ ]7 ↑head=0 ↑tail=38
9After addFirst(0):10[ 1, 2, 3, _, _, _, _, 0 ] 0 wraps to the end11 ↑head=7 (wraps) ↑tail=3Code Example ArrayDeque as a Queue
1import java.util.ArrayDeque;2import java.util.Deque;3
4public class ArrayDequeAsQueue {5 public static void main(String[] args) {6 Deque<Integer> queue = new ArrayDeque<>();7
8 // FIFO insertion — add at the back9 queue.addLast(1); // [1]10 queue.addLast(5); // [1, 5]11 queue.addLast(10); // [1, 5, 10]12
13 // FIFO removal — remove from the front14 System.out.println(queue.removeFirst()); // 115 System.out.println(queue.removeFirst()); // 516 System.out.println(queue.removeFirst()); // 1017 }18}Output
1125310Code Example ArrayDeque as a Stack
1import java.util.ArrayDeque;2import java.util.Deque;3
4public class ArrayDequeAsStack {5 public static void main(String[] args) {6 Deque<Integer> stack = new ArrayDeque<>();7
8 // LIFO insertion — add at the front9 stack.addFirst(1); // [1]10 stack.addFirst(5); // [5, 1]11 stack.addFirst(10); // [10, 5, 1]12
13 // LIFO removal — remove from the front14 System.out.println(stack.removeFirst()); // 1015 System.out.println(stack.removeFirst()); // 516 System.out.println(stack.removeFirst()); // 117 }18}Output
11025315. ArrayDeque Time Complexity & Thread Safety
Time Complexity
| Operation | Complexity | Notes |
|---|---|---|
Insert at front (addFirst) | O(1) amortized | O(n) on resize |
Insert at back (addLast) | O(1) amortized | O(n) on resize |
Remove from front (removeFirst) | O(1) | Always |
Remove from back (removeLast) | O(1) | Always |
Examine front/back (peekFirst/peekLast) | O(1) | Always |
| Search (contains) | O(n) | Must traverse |
| Space | O(n) | n = number of elements |
What Does "Amortized O(1)" Mean?
Amortized O(1) means the average time complexity per operation over many operations is O(1), even though occasional operations are slower.
The expensive case happens when the internal array is full:
1Step 1: Array is full [1, 2, 3, 4, 5, 6, 7, 8] — capacity 82Step 2: Resize — create new array of size 163Step 3: Copy all 8 elements → O(n) for this one operation4Step 4: Insert new element → O(1)This O(n) resize happens rarely — only when the array doubles. On average across all insertions, the cost per insert is still O(1).
Thread Safety & Concurrent Versions
| Class | Thread Safe? | Notes |
|---|---|---|
ArrayDeque | ❌ No | Use in single-threaded code |
ConcurrentLinkedDeque | ✅ Yes | Thread-safe deque; non-blocking |
ConcurrentLinkedDeque Example
1import java.util.concurrent.ConcurrentLinkedDeque;2
3public class ConcurrentDequeExample {4 public static void main(String[] args) {5 ConcurrentLinkedDeque<Integer> deque = new ConcurrentLinkedDeque<>();6
7 // Same methods as ArrayDeque — but thread-safe8 deque.addFirst(10);9 deque.addLast(20);10 System.out.println(deque.pollFirst()); // 1011 System.out.println(deque.pollLast()); // 2012 }13}ArrayDeque (or PriorityQueue) in a multi-threaded environment where multiple threads can access the same queue concurrently. Use ConcurrentLinkedDeque (for deque) or PriorityBlockingQueue (for priority queue) instead.6. The `List` Interface
Overview
List is an interface that extends Collection. It represents an ordered collection where:
- Elements are accessed by integer index (starting from
0) - Duplicate elements are allowed
nullelements are allowed (in most implementations)- Data can be inserted, removed, or accessed from any position
How List Differs from Queue
This is a key conceptual distinction:
| Feature | Queue / Deque | List |
|---|---|---|
| Access | Front or back only | Any index |
| Internal structure | Circular array / linked nodes | Array or linked list with index |
| Removal | Front or back | Any index |
| Insertion | Front or back | Any index |
| Index-based access | ❌ No | ✅ Yes |
Real-world Analogy
A List is like a numbered shelf in a library. You can place a book at shelf #3, remove the book from shelf #7, or look at the book on shelf #0 — accessing any position directly by its number.
Position in the Hierarchy
7. List Methods Complete Reference
The List interface includes all methods inherited from Collection plus the following new index-aware methods:
New Methods Added by `List`
| Method | Description |
|---|---|
add(int index, E element) | Inserts element at the given index; shifts all subsequent elements right |
addAll(int index, Collection c) | Inserts all elements of collection c starting at given index; shifts subsequent elements right |
get(int index) | Returns element at the given index |
set(int index, E element) | Replaces (does NOT shift) the element at the given index; returns the old element |
remove(int index) | Removes and returns element at given index; shifts subsequent elements left |
indexOf(Object o) | Returns index of first occurrence of o; returns -1 if not found |
lastIndexOf(Object o) | Returns index of last occurrence of o; returns -1 if not found |
replaceAll(UnaryOperator | Applies the given function to every element in place (Java 1.8) |
sort(Comparator | Sorts the list using the given comparator |
listIterator() | Returns a ListIterator starting at index 0 |
listIterator(int index) | Returns a ListIterator starting at the given index |
subList(int from, int to) | Returns a view of the list from from (inclusive) to to (exclusive) |
Critical Difference: `add(index, e)` vs. `set(index, e)`
1List before: [100, 200, 300, 400]2Indices: 0 1 2 33
4After add(2, 999): // Shifts elements right — list GROWS5[100, 200, 999, 300, 400]6 0 1 2 3 47
8After set(2, 999): // Replaces element — list size unchanged9[100, 200, 999, 400]10 0 1 2 3add(index, element) → inserts; existing element at that index shifts to the right; list grows by 1
- set(index, element) → replaces; existing element is overwritten; list size stays the sameCritical Difference: `remove(int index)` vs. `remove(Object o)`
1List<Integer> list = new ArrayList<>(Arrays.asList(10, 20, 30, 40));2
3list.remove(2); // Removes by INDEX → removes 30 (index 2)4list.remove(Integer.valueOf(10)); // Removes by OBJECT VALUE → removes 10list.remove(3) with a primitive int removes by index.
list.remove(Integer.valueOf(3)) with an Integer object removes by value.
This is a very common source of bugs.`subList()` Important Behavior
subList(fromIndex, toIndex) returns a live view (not a copy) of the original list.
1List<Integer> main = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));2List<Integer> sub = main.subList(1, 4); // [1, 2, 3] (indices 1 inclusive to 4 exclusive)3
4sub.remove(Integer.valueOf(2)); // Removes from sub AND from main!5System.out.println(main); // [0, 1, 3, 4, 5]subList is immediately reflected in the original list, and vice versa. They share the same underlying data.Complete Code Example All List Methods
1import java.util.ArrayList;2import java.util.Arrays;3import java.util.List;4
5public class ListMethodsExample {6 public static void main(String[] args) {7
8 // ── add(index, element) ──9 List<Integer> list1 = new ArrayList<>();10 list1.add(0, 100); // [100]11 list1.add(1, 200); // [100, 200]12 list1.add(3, 300); // IndexOutOfBoundsException! index 3 doesn't exist yet13 }14}add at an index that already exists OR at the index equal to size() (appending). Adding at index 3 when size is 2 throws IndexOutOfBoundsException.1import java.util.ArrayList;2import java.util.List;3
4public class ListMethodsExample {5 public static void main(String[] args) {6
7 // Build the list step by step8 List<Integer> list1 = new ArrayList<>();9 list1.add(0, 100); // [100]10 list1.add(1, 200); // [100, 200]11 list1.add(2, 300); // [100, 200, 300]12 list1.add(2, 300); // [100, 200, 300, 300] — duplicate, valid13
14 // ── addAll(index, collection) ──15 List<Integer> list2 = new ArrayList<>();16 list2.add(400);17 list2.add(500);18 list2.add(600);19 // list2 = [400, 500, 600]20
21 list1.addAll(2, list2);22 // Inserts list2 starting at index 2 and shifts remaining elements right23 // list1 = [100, 200, 400, 500, 600, 300, 300]24
25 System.out.println("After addAll: " + list1);26
27 // ── replaceAll(UnaryOperator) ──28 // Multiply every element by -129 list1.replaceAll(value -> value * -1);30 System.out.println("After replaceAll (*-1): " + list1);31 // [-100, -200, -400, -500, -600, -300, -300]32
33 // ── sort(Comparator) ──34 list1.sort((v1, v2) -> v1 - v2); // ascending order35 System.out.println("After sort (ascending): " + list1);36 // [-600, -500, -400, -300, -300, -200, -100]37
38 // ── get(index) ──39 System.out.println("Element at index 2: " + list1.get(2)); // -40040
41 // ── set(index, element) — REPLACES, does not shift ──42 list1.set(2, -4000);43 System.out.println("After set(2, -4000): " + list1);44 // [-600, -500, -4000, -300, -300, -200, -100]45
46 // ── remove(index) — removes and shifts remaining left ──47 list1.remove(2); // removes -400048 System.out.println("After remove(2): " + list1);49 // [-600, -500, -300, -300, -200, -100]50
51 // ── indexOf(Object) ──52 System.out.println("First index of -300: " + list1.indexOf(Integer.valueOf(-300))); // 253 System.out.println("Last index of -300: " + list1.lastIndexOf(Integer.valueOf(-300))); // 354 }55}Output
1After addAll: [100, 200, 400, 500, 600, 300, 300]2After replaceAll (*-1): [-100, -200, -400, -500, -600, -300, -300]3After sort (ascending): [-600, -500, -400, -300, -300, -200, -100]4Element at index 2: -4005After set(2, -4000): [-600, -500, -4000, -300, -300, -200, -100]6After remove(2): [-600, -500, -300, -300, -200, -100]7First index of -300: 28Last index of -300: 38. The `ListIterator`
Overview
ListIterator is a specialized iterator returned by List.listIterator(). It extends the standard Iterator and adds the ability to:
- Traverse the list in both directions (forward and backward)
- Modify elements during iteration (
set()) - Insert elements during iteration (
add()) - Query the index of the next and previous elements
Hierarchy
Complete Method Reference
| Method | Direction | Description |
|---|---|---|
hasNext() | Forward | Returns true if there are more elements in the forward direction |
next() | Forward | Returns next element and advances cursor forward |
hasPrevious() | Backward | Returns true if there are more elements in the backward direction |
previous() | Backward | Returns previous element and moves cursor backward |
nextIndex() | — | Returns the index of the element that would be returned by next() |
previousIndex() | — | Returns the index of the element that would be returned by previous() |
remove() | — | Removes the last element returned by next() or previous() |
set(E e) | — | Replaces the last element returned by next() or previous() |
add(E e) | — | Inserts element immediately before the element that would be returned by next() |
Understanding the Cursor
The ListIterator cursor sits between elements, not on them:
1List: [-600, -500, -300, -200, -100]2 0 1 2 3 43
4Cursor positions (marked with |):5| -600 | -500 | -300 | -200 | -100 |6^pos0 pos1 pos2 pos3 pos4 ^pos57
8At position 2 (cursor between index 1 and 2):9 previous() → returns -500 (index 1), cursor moves to pos110 next() → returns -300 (index 2), cursor moves to pos311 previousIndex() → 112 nextIndex() → 2Code Example Forward Traversal with ListIterator
1import java.util.ArrayList;2import java.util.List;3import java.util.ListIterator;4
5public class ListIteratorForward {6 public static void main(String[] args) {7 List<Integer> list = new ArrayList<>();8 list.add(-600);9 list.add(-500);10 list.add(-300);11 list.add(-200);12 list.add(-100);13 // list = [-600, -500, -300, -200, -100]14
15 // listIterator() with no argument — cursor starts at position 0 (before index 0)16 ListIterator<Integer> it = list.listIterator();17
18 while (it.hasNext()) {19 Integer value = it.next();20 System.out.println("Value: " + value21 + " | nextIndex: " + it.nextIndex()22 + " | prevIndex: " + it.previousIndex());23
24 // When we reach -200, insert -100 before the next element25 if (value.equals(-200)) {26 it.add(-150);27 // Inserts -150 before -100 (what next() would return)28 // list becomes [-600, -500, -300, -200, -150, -100]29 // Subsequent calls to next() are NOT affected — next() still returns -10030 }31 }32
33 System.out.println("Final list: " + list);34 }35}Output
1Value: -600 | nextIndex: 1 | prevIndex: 02Value: -500 | nextIndex: 2 | prevIndex: 13Value: -300 | nextIndex: 3 | prevIndex: 24Value: -200 | nextIndex: 4 | prevIndex: 35Value: -100 | nextIndex: 6 | prevIndex: 56Final list: [-600, -500, -300, -200, -150, -100]How `add()` During ListIterator Works
1Before add(-150):2Cursor is between -200 and -1003[ -600, -500, -300, -200, | , -100 ]4 ↑ cursor here5
6After it.add(-150):7[ -600, -500, -300, -200, -150, -100 ]8 ↑ next() will return -100 (unaffected)9 ↑ previous() would return -150it.add(e), the newly inserted element becomes what previous() would return. The next() call is not affected — it still returns what it would have before the insert.Code Example Backward Traversal with ListIterator
1import java.util.ArrayList;2import java.util.List;3import java.util.ListIterator;4
5public class ListIteratorBackward {6 public static void main(String[] args) {7 List<Integer> list = new ArrayList<>();8 list.add(-600);9 list.add(-500);10 list.add(-300);11 list.add(-200);12 list.add(-100);13 // list = [-600, -500, -300, -200, -100]14
15 // listIterator(size) — cursor starts at the END (after last element)16 ListIterator<Integer> it = list.listIterator(list.size());17
18 while (it.hasPrevious()) {19 Integer value = it.previous();20 System.out.println("Value: " + value21 + " | nextIndex: " + it.nextIndex()22 + " | prevIndex: " + it.previousIndex());23
24 // Replace -100 with -5025 if (value.equals(-100)) {26 it.set(-50);27 // Replaces last element returned by previous() (which was -100) with -5028 }29 }30
31 System.out.println("Final list: " + list);32 }33}Output
1Value: -100 | nextIndex: 4 | prevIndex: 32Value: -200 | nextIndex: 3 | prevIndex: 23Value: -300 | nextIndex: 2 | prevIndex: 14Value: -500 | nextIndex: 1 | prevIndex: 05Value: -600 | nextIndex: 0 | prevIndex: -16Final list: [-600, -500, -300, -200, -50]listIterator(list.size()) places the cursor at the very end, so hasPrevious() will return true and previous() will return the last element.9. ArrayList Concrete Implementation
Overview
ArrayList is the most commonly used List implementation. It is backed by a dynamic array that grows automatically as elements are added.
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | Resizable array |
| Initial capacity | 10 elements (default) |
| Growth factor | Approximately 1.5× when full |
| Thread-safe | ❌ No |
| Null elements | ✅ Allowed |
| Duplicate elements | ✅ Allowed |
| Maintains insertion order | ✅ Yes |
Internal Resizing
1Initial: [_, _, _, _, _, _, _, _, _, _] capacity = 102After 10 adds: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] full3
4Add 11th element triggers resize:5New capacity ≈ 10 * 1.5 = 156New array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, _, _, _, _]ArrayDeque starts at capacity 8 and doubles. ArrayList starts at capacity 10 and grows by approximately 1.5×. Both use amortized O(1) insertion at the end.Complete Code Example
1import java.util.ArrayList;2import java.util.Collections;3import java.util.List;4
5public class ArrayListExample {6 public static void main(String[] args) {7 List<Integer> list = new ArrayList<>();8
9 // ── Basic add ──10 list.add(30);11 list.add(10);12 list.add(20);13 list.add(10); // duplicate allowed14 list.add(null); // null allowed15 // list = [30, 10, 20, 10, null]16
17 System.out.println("Size: " + list.size()); // 518 System.out.println("Get index 2: " + list.get(2)); // 2019
20 // ── Sort (ignoring null for simplicity) ──21 list.remove(null);22 list.sort((a, b) -> a - b);23 System.out.println("Sorted: " + list); // [10, 10, 20, 30]24
25 // ── Thread-safe version ──26 // Use CopyOnWriteArrayList for multi-threaded access27 // java.util.concurrent.CopyOnWriteArrayList<Integer> safeList =28 // new java.util.concurrent.CopyOnWriteArrayList<>(list);29 }30}10. ArrayList Time Complexity & Thread Safety
Time Complexity
| Operation | Complexity | Reason |
|---|---|---|
add(e) — append at end | O(1) amortized | Array has space; O(n) on resize |
add(index, e) — insert at index | O(n) | Must shift all subsequent elements right |
get(index) | O(1) | Direct array index access |
set(index, e) | O(1) | Direct array index access |
remove(index) | O(n) | Must shift all subsequent elements left |
contains(o) / indexOf(o) | O(n) | Must scan the array linearly |
size(), isEmpty() | O(1) | Cached field |
| Space | O(n) | One slot per element |
Why Insertion/Deletion at Index is O(n)
1List: [10, 20, 30, 40, 50] Insert 99 at index 22
3Step 1: Shift elements right from index 2 onward4[10, 20, 30, 30, 40, 50] (copy 50→index5, 40→index4, 30→index3)5Step 2: Place 99 at index 26[10, 20, 99, 30, 40, 50]7
8Worst case (insert at index 0): shift ALL n elements → O(n)Thread Safety
| Variant | Thread Safe? | Notes |
|---|---|---|
ArrayList | ❌ No | Fast; use in single-threaded contexts |
Collections.synchronizedList(new ArrayList<>()) | ✅ Yes (with manual sync on iteration) | Wraps each method with synchronized |
CopyOnWriteArrayList | ✅ Yes | Each mutation creates a fresh copy of the array; great for read-heavy, write-rare scenarios |
11. LinkedList Concrete Implementation
Overview
LinkedList is unique because it implements both List and Deque. This means it can function as:
- An index-based list (like
ArrayList) - A double-ended queue (like
ArrayDeque) - A stack
- A queue
Internal Data Structure
LinkedList is backed by a doubly linked list. Each element is stored in a Node object:
1// Internal Node structure (simplified)2private static class Node<E> {3 E item;4 Node<E> next; // pointer to next node5 Node<E> prev; // pointer to previous node6}1head tail2 ↓ ↓3[null ← 100 ⇄ 200 ⇄ 300 ⇄ 400 → null]4 0 1 2 3Key Characteristics
| Feature | Value |
|---|---|
| Backed by | Doubly linked list nodes |
| Thread-safe | ❌ No |
| Null elements | ✅ Allowed |
| Duplicate elements | ✅ Allowed |
| Maintains insertion order | ✅ Yes |
| Index-based access | ✅ Yes (but O(n) to traverse) |
Code Example LinkedList as Deque
1import java.util.LinkedList;2
3public class LinkedListAsDeque {4 public static void main(String[] args) {5 LinkedList<Integer> deque = new LinkedList<>();6
7 // Add using Deque methods8 deque.addLast(200); // [200]9 deque.addLast(300); // [200, 300]10 deque.addLast(400); // [200, 300, 400]11 deque.addFirst(100); // [100, 200, 300, 400]12
13 System.out.println("First: " + deque.getFirst()); // 10014 System.out.println("Last: " + deque.getLast()); // 40015 }16}Code Example LinkedList as List (Index-based)
1import java.util.LinkedList;2import java.util.List;3
4public class LinkedListAsList {5 public static void main(String[] args) {6 List<Integer> list = new LinkedList<>();7
8 // Add using index9 list.add(0, 100); // [100]10 list.add(1, 300); // [100, 300]11 list.add(2, 400); // [100, 300, 400]12 list.add(1, 200); // [100, 200, 300, 400] (inserts at index 1, shifts right)13
14 // Get by index15 System.out.println("Index 1: " + list.get(1)); // 20016 System.out.println("Index 2: " + list.get(2)); // 30017 }18}How Insertion at Index Works in LinkedList
1Insert 200 at index 1 in [100 → 300 → 400]:2
3Step 1: Traverse from head to index 1 → O(n) for lookup4Step 2: Create new node for 2005Step 3: Update pointers (O(1)):6 100.next = 2007 200.next = 3008 300.prev = 2009 200.prev = 10010
11Result: [100 ⇄ 200 ⇄ 300 ⇄ 400]12. LinkedList Time Complexity & Thread Safety
Time Complexity
| Operation | Complexity | Reason |
|---|---|---|
Insert at head (addFirst) | O(1) | Update head pointer only |
Insert at tail (addLast) | O(1) | Update tail pointer only |
| Insert at index | O(n) | O(n) to traverse to index + O(1) to link nodes |
| Remove from head | O(1) | Update head pointer only |
| Remove from tail | O(1) | Update tail pointer only |
| Remove at index | O(n) | O(n) to traverse to index + O(1) to unlink node |
get(index) | O(n) | Must traverse from head to index |
contains(o) | O(n) | Must traverse the entire list |
| Space | O(n) | Each element has a Node with two pointers |
ArrayList vs. LinkedList Comparison
| Operation | ArrayList | LinkedList | Winner |
|---|---|---|---|
| Add at end | O(1) amortized | O(1) | Tie |
| Add at beginning | O(n) | O(1) | LinkedList ✅ |
| Add at index | O(n) | O(n) | Tie |
| Get by index | O(1) | O(n) | ArrayList ✅ |
| Remove at end | O(1) | O(1) | Tie |
| Remove at beginning | O(n) | O(1) | LinkedList ✅ |
| Memory overhead | Low (array) | High (Node objects + 2 pointers each) | ArrayList ✅ |
ArrayList when you frequently read by index or append to the end.
Use LinkedList when you frequently insert or remove from the beginning or middle, and do not need random index access.Thread Safety
| Variant | Thread Safe? |
|---|---|
LinkedList | ❌ No |
Collections.synchronizedList(new LinkedList<>()) | ✅ Yes |
13. Vector Thread-Safe List
Overview
Vector is a legacy class (Java 1.0) that works exactly like ArrayList but with one key difference: every method is synchronized, making it thread-safe out of the box.
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | Resizable array (same as ArrayList) |
| Thread-safe | ✅ Yes — all methods synchronized |
| Null elements | ✅ Allowed |
| Duplicate elements | ✅ Allowed |
| Maintains insertion order | ✅ Yes |
| Performance vs ArrayList | ❌ Slower — synchronization adds overhead even in single-threaded code |
Why Vector is Slower
Every method in Vector acquires a lock before executing and releases it after. Even in single-threaded code where no locking is needed, the lock/unlock overhead is paid on every operation.
1// From the Vector source code — every method is synchronized:2public synchronized boolean add(E e) { ... }3public synchronized E get(int index) { ... }4public synchronized E remove(int index) { ... }5public synchronized int indexOf(Object o) { ... }6// ... and so on for every methodCode Example
1import java.util.Vector;2
3public class VectorExample {4 public static void main(String[] args) {5 Vector<Integer> vector = new Vector<>();6
7 // Exact same API as ArrayList8 vector.add(10);9 vector.add(20);10 vector.add(30);11
12 System.out.println(vector.get(1)); // 2013 System.out.println(vector.size()); // 314 System.out.println(vector.contains(20)); // true15
16 vector.remove(Integer.valueOf(20));17 System.out.println(vector); // [10, 30]18 }19}Vector has no separate thread-safe version — it is the thread-safe version. Its child class Stack inherits this thread safety.14. Stack Thread-Safe LIFO
Overview
Stack extends Vector and represents a Last In, First Out (LIFO) data structure. Because it extends Vector, all its methods are also synchronized (thread-safe).
Position in Hierarchy
1Vector (thread-safe ArrayList)2 └── Stack (LIFO, inherits thread-safety)How LIFO Works
1Push sequence: 1, 2, 3, 42Stack state (top at right): [1, 2, 3, 4]3 ↑ top4
5Pop sequence: 4, 3, 2, 1 (last pushed = first popped)Stack-Specific Methods
| Method | Description |
|---|---|
push(e) | Pushes element onto the top of the stack |
pop() | Removes and returns the top element; throws EmptyStackException if empty |
peek() | Returns (but does NOT remove) the top element |
empty() | Returns true if the stack is empty |
search(o) | Returns 1-based position from the top; -1 if not found |
Code Example
1import java.util.Stack;2
3public class StackExample {4 public static void main(String[] args) {5 Stack<Integer> stack = new Stack<>();6
7 // Push elements8 stack.push(1); // [1]9 stack.push(2); // [1, 2]10 stack.push(3); // [1, 2, 3]11 stack.push(4); // [1, 2, 3, 4]12
13 System.out.println("Peek: " + stack.peek()); // 4 (top, not removed)14 System.out.println("Pop: " + stack.pop()); // 4 (removed)15 System.out.println("Pop: " + stack.pop()); // 316 System.out.println("Empty: " + stack.empty()); // false17 System.out.println("Pop: " + stack.pop()); // 218 System.out.println("Pop: " + stack.pop()); // 119 System.out.println("Empty: " + stack.empty()); // true20 }21}Output
1Peek: 42Pop: 43Pop: 34Empty: false5Pop: 26Pop: 17Empty: trueTime Complexity
| Operation | Complexity | Reason |
|---|---|---|
push(e) | O(1) | Add to top (end of underlying array) |
pop() | O(1) | Remove from top |
peek() | O(1) | Read top without removal |
search(o) | O(n) | Linear scan from top |
| Space | O(n) | n elements |
Stack Properties Table
| Feature | Value |
|---|---|
| Thread-safe | ✅ Yes (inherits from Vector) |
| Null elements | ✅ Allowed |
| Duplicate elements | ✅ Allowed |
| Maintains insertion order | Technically yes, but the access order is reversed (LIFO) |
| Preferred modern alternative | ArrayDeque used as a stack (not thread-safe but faster) |
Stack means the internal array stores elements in push order. However, when you pop(), you get them in reverse order. This is the definition of LIFO — it's intentional, not a loss of order.15. Comparison Table All Implementations
| Class | Implements | Backed By | Thread-Safe | Null OK | Duplicates | Random Access | Insert/Remove Front | Insert/Remove End |
|---|---|---|---|---|---|---|---|---|
ArrayDeque | Deque | Circular array | ❌ | ❌ | ✅ | ❌ | O(1) | O(1) amortized |
ConcurrentLinkedDeque | Deque | Linked nodes | ✅ | ❌ | ✅ | ❌ | O(1) | O(1) |
ArrayList | List | Array | ❌ | ✅ | ✅ | O(1) | O(n) | O(1) amortized |
CopyOnWriteArrayList | List | Array (copy-on-write) | ✅ | ✅ | ✅ | O(1) | O(n) | O(n) |
LinkedList | List, Deque | Doubly linked nodes | ❌ | ✅ | ✅ | O(n) | O(1) | O(1) |
Vector | List | Array | ✅ | ✅ | ✅ | O(1) | O(n) | O(1) amortized |
Stack | (extends Vector) | Array | ✅ | ✅ | ✅ | O(1) | O(n) push/pop=O(1) | O(1) |
16. Interview Notes
Q1: What is a Deque? How is it different from a Queue?
A: A Queue only allows insertion at the back and removal from the front (FIFO). A Deque (Double Ended Queue) allows insertion and removal at both the front and back. Deque extends Queue and adds addFirst, addLast, removeFirst, removeLast, and their peek/poll equivalents.
Q2: How can you implement a Stack using Deque?
A: Use push(e) (which calls addFirst) to add elements, and pop() (which calls removeFirst) to remove them. Since both add and remove happen at the same end (front), the behavior is LIFO.
1Deque<Integer> stack = new ArrayDeque<>();2stack.push(1); stack.push(2); stack.push(3);3stack.pop(); // returns 3 — LIFOQ3: Why is `ArrayDeque` preferred over `Stack` for stack operations?
A: Stack extends the legacy Vector class whose every method is synchronized. This synchronization overhead makes it slower, even in single-threaded programs where no thread safety is needed. ArrayDeque has no synchronization and is significantly faster. Java's own documentation recommends ArrayDeque for stack use cases.
Q4: What is the difference between `List` and `Queue`?
A: A Queue supports insertion/removal only at the front or back. A List supports insertion, removal, and access at any index. List provides get(index), set(index, e), add(index, e), remove(index) — none of which exist in Queue.
Q5: What is the difference between `add(index, e)` and `set(index, e)` in List?
A:
add(index, e): inserts at the index, shifting all subsequent elements right. List grows by 1.set(index, e): replaces the element at the index. List size unchanged. Returns the old element.
Q6: What is `ListIterator` and how is it different from `Iterator`?
A: ListIterator extends Iterator and adds:
- Backward traversal (
hasPrevious(),previous()) - Index querying (
nextIndex(),previousIndex()) - In-place modification (
set(e)) - Insertion during iteration (
add(e))
Iterator only supports forward traversal and removal.
Q7: What is the difference between `ArrayList` and `LinkedList`?
A:
ArrayList | LinkedList | |
|---|---|---|
| Backed by | Array | Doubly linked nodes |
get(index) | O(1) | O(n) |
| Insert at front | O(n) | O(1) |
| Insert at end | O(1) amortized | O(1) |
| Memory | Less (plain array) | More (Node objects + 2 pointers each) |
| Implements Deque? | ❌ | ✅ |
Use ArrayList when you need fast random access. Use LinkedList when you frequently insert/remove from the front or middle.
Q8: What is the difference between `Vector` and `ArrayList`?
A: Both are backed by a resizable array with the same API. The only difference:
Vector: every method issynchronized→ thread-safe but slowerArrayList: not synchronized → faster in single-threaded code
Vector is a legacy class (Java 1.0). For new code, prefer ArrayList + CopyOnWriteArrayList (for thread safety).
Q9: What are the thread-safe versions of each collection?
| Collection | Thread-Safe Version |
|---|---|
ArrayList | CopyOnWriteArrayList |
ArrayDeque | ConcurrentLinkedDeque |
PriorityQueue | PriorityBlockingQueue |
LinkedList | Collections.synchronizedList(new LinkedList<>()) |
Vector | Already thread-safe (itself) |
Stack | Already thread-safe (extends Vector) |
Q10: Can `ArrayDeque` contain null elements? Can `ArrayList`?
A:
ArrayDeque: No — null elements are not permitted. Methods likepeek()returnnullto indicate an empty deque, so null elements would create ambiguity.ArrayList: Yes — null elements are allowed.
Q11: What does `subList()` return and what is its important behavior?
A: subList(fromIndex, toIndex) returns a live view (not a copy) of the specified portion of the list. Any structural change to the sublist is immediately reflected in the original list and vice versa. Modifying the original list while holding a sublist reference may cause unexpected behavior.
17. Summary & Quick Revision
Key Revision Bullets
- Deque = Double Ended Queue; extends
Queue; insertion + removal at both ends. add/remove/getprefix → throw exception;offer/poll/peekprefix → return false/null.push(e)callsaddFirst;pop()callsremoveFirst— enabling stack behavior.ArrayDeque: circular array; O(1) amortized insert at either end; not thread-safe; no null elements.ConcurrentLinkedDeque= thread-safeArrayDequeequivalent.List: ordered, index-based, allows duplicates and nulls (most implementations).add(index, e)→ shifts right (list grows).set(index, e)→ replaces (size unchanged).remove(int)= by index.remove(Integer.valueOf(n))= by value.subList()returns a live view — mutations affect the original.ListIterator= bidirectional iterator withset()andadd()during iteration.ArrayList: O(1)get, O(n) insert/remove at index;CopyOnWriteArrayList= thread-safe version.LinkedList: O(1) front/back ops, O(n) random access; implements bothListandDeque.Vector: synchronizedArrayList; thread-safe but slower; legacy class.Stack: extendsVector; LIFO; thread-safe; preferArrayDequefor single-threaded stack use.
18. Practice Questions
Easy
- What does "Deque" stand for and what makes it different from a regular queue?
- Which method in
Dequeinserts an element at the front and throws an exception on failure? - What is the difference between
pollFirst()andremoveFirst()? - In a
List, what index does the first element have? - What does
list.get(2)return for a list[10, 20, 30, 40]? - True or False:
ArrayListmaintains insertion order. - True or False:
ArrayDequeallowsnullelements. - Which collection is the thread-safe version of
ArrayList?
Medium
- Write code to use
ArrayDequeas a queue AND as a stack (two separate demonstrations). - Explain with a code example the difference between
add(index, e)andset(index, e). - Write code to iterate a
Listin reverse usingListIterator. - What is
subList()and what happens when you modify the returned list? - Why is
LinkedListfaster thanArrayListfor insertions at the front? - Explain what "amortized O(1)" means using
ArrayDeque's resize behavior as an example. - Write code to remove all negative numbers from a
ListusingListIterator.
Hard
LinkedListimplements bothListandDeque. Write code that uses the sameLinkedListobject for both index-basedListoperations andaddFirst/removeLastDequeoperations simultaneously.- Explain why
remove(int)andremove(Integer)behave differently onListat the bytecode level. What does Java's method resolution do? - Compare the memory layout of
ArrayListvsLinkedListfor storing 1,000 integers. Which uses more memory and why? - Implement a palindrome checker using
ArrayDeque— push each character, then pop from both ends to verify. - When would you choose
CopyOnWriteArrayListoverCollections.synchronizedList(new ArrayList<>())? Discuss trade-offs in read-heavy vs. write-heavy scenarios.
Set implementations (HashSet, LinkedHashSet, TreeSet), the Map hierarchy (HashMap, LinkedHashMap, TreeMap), and finally the Streams API (Java 1.8) — which will be covered in a dedicated section due to its depth and importance.Mastery check
How well can you recall this?
Finished this lesson?