KNOWLEDGEWALA • LEARN TEACH GROW • JAVA INTERVIEW SERIES

Java Collections
Framework — Complete Tutorial

From ArrayList vs LinkedList to HashMap internals, TreeMap, ConcurrentHashMap, Streams & LeetCode patterns — one tutorial you can read, learn, understand, and explain in an interview.

⏱ 100–130 min read📚 10 Chapters💻 25+ Runnable Programs🎯 Low → High Complexity⭐ 12 LeetCode Problems

📑 Table of Contents

  1. Chapter 1 — Why Collections? Array vs Collection
  2. Chapter 2 — Collection Hierarchy: List, Set, Queue, Map, Deque
  3. Chapter 3 — List: ArrayList vs LinkedList vs Vector vs CopyOnWrite
  4. Chapter 4 — Set: HashSet vs LinkedHashSet vs TreeSet
  5. Chapter 5 — Map: HashMap Internals, LinkedHashMap, TreeMap, WeakHashMap
  6. Chapter 6 — Queue, Deque, PriorityQueue, Stack
  7. Chapter 7 — equals() & hashCode() Contract — The #1 Interview Trap
  8. Chapter 8 — Sorting, Comparable vs Comparator, Collections Utility
  9. Chapter 9 — Concurrent Collections, Fail-Fast vs Fail-Safe, Streams
  10. Chapter 10 — Real-Time Systems, LeetCode Patterns & Interview Plan

How to use: For every collection — Theory → Analogy → When to use → Internal Working → Time Complexity → Complete Runnable Code → Real-Time Use → LeetCode → Interview Line.

How To Read • For Everyone

Read This First — 2 Minutes That Will Save You 2 Hours

👩‍🎓 Student
Read Analogy + When to use + Easy Code. Focus Ch 1–4. Do not worry about HashMap internals on first read.
👨‍💻 Junior
Read Problem → Easy → Optimized. Focus Ch 3, 5, 7, 8. These cover 80% of interviews.
🧑‍🏫 Expert / Senior
Jump to Expert Notes + Internals + Concurrent + Streams. Focus Ch 5, 9, 10.
🧑‍💼 Non-Tech
Read only Analogy + Real-Time + One-Line Answer. Skip code. You will understand why engineers choose List vs Set vs Map.
Expert Tutor Rule: Never learn a collection without 4 things — 1) A story, 2) When to use / when NOT to use, 3) Internal working + Big-O, 4) A code you can type.

The 3 Questions That Choose Any Collection

QuestionIf YES → Use
Do you need key → value lookup?Map — HashMap / TreeMap
Do you need duplicates? Order matters?List — ArrayList / LinkedList
Do you need unique values only?Set — HashSet / TreeSet
Do you need FIFO / Priority processing?Queue — ArrayDeque / PriorityQueue
Chapter 1 • Beginner • Why Collections?

Why Collections? Array vs Collection Framework

Arrays are fixed, hard to use, and have no ready methods. Collections are dynamic, rich, and interview-ready.

🏪 Non-Tech Analogy: Array = A shelf with exactly 10 slots. If you need 11th item, you must buy a new shelf and move everything. Collection = A smart shelf that grows itself, tells you if item exists, removes item, sorts items — automatically.

1.1 Array Problems — Why Collections Were Invented

Array ProblemCollection Solution
Fixed size — new int[10] cannot growArrayList grows automatically (1.5x)
No methods — search, sort, remove manuallyReady methods: add, remove, contains, sort
Only primitives + objects, no genericsGenerics: List<String> — type-safe
No Set / Map / Queue built-inFull framework: List, Set, Map, Queue, Deque

1.2 Complete Program — Array vs ArrayList

import java.util.*;
public class ArrayVsCollectionComplete {
    public static void main(String[] args) {
        // ARRAY: fixed, manual work
        String[] arr = new String[2];
        arr[0] = "A"; arr[1] = "B";
        // arr[2] = "C"; // ArrayIndexOutOfBoundsException — cannot grow!
        System.out.println("Array length fixed: " + arr.length);

        // COLLECTION: dynamic, easy
        List<String> list = new ArrayList<>();
        list.add("A"); list.add("B"); list.add("C"); list.add("D"); // grows automatically
        System.out.println("List: " + list + " size=" + list.size());
        System.out.println("Contains C? " + list.contains("C"));
        list.remove("B");
        System.out.println("After remove B: " + list);
        Collections.sort(list);
        System.out.println("Sorted: " + list);
        // Generics: List<String> cannot add Integer — compile error, type-safe
        // list.add(123); // COMPILE ERROR — good!
    }
}

1.3 What is Collection Framework?

A set of interfaces + classes + algorithms in java.util to store and process groups of objects. Interfaces = contract (what to do). Classes = implementation (how to do). Algorithms = utility methods (sort, search, shuffle).

🗣 Interview Q: What is Collection Framework? Answer: “A unified architecture in java.util for storing and manipulating groups of objects — interfaces (List, Set, Map), implementations (ArrayList, HashSet, HashMap), and algorithms (Collections.sort, binarySearch).”
Chapter 2 • Beginner • Hierarchy

Collection Hierarchy: List, Set, Queue, Map, Deque

Collection (interface) — root for List, Set, Queue
├── List — Ordered, allows duplicates, index-based
│   ├── ArrayList, LinkedList, Vector, Stack, CopyOnWriteArrayList
├── Set — No duplicates
│   ├── HashSet, LinkedHashSet, TreeSet, EnumSet
├── Queue — FIFO / Priority
│   ├── PriorityQueue, ArrayDeque, LinkedList (also Queue)
└── Deque — Double-ended queue (add/remove both ends)
    └── ArrayDeque, LinkedList

Map (interface) — NOT part of Collection, separate root
├── HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap, WeakHashMap

2.1 One-Line for Each Interface

InterfaceOrder?Duplicates?Example
ListYes, insertion orderYesShopping cart, to-do list
SetHashSet: No. LinkedHashSet: Yes. TreeSet: SortedNoUnique emails, unique tags
QueueFIFO / PriorityYesPrint queue, task queue
DequeBoth endsYesUndo/Redo, browser history
MapHashMap: No. LinkedHashMap: Yes. TreeMap: Sorted keysKeys: No, Values: YesUserId → User, Word → Count
📚 Non-Tech Analogy: List = Class attendance register (order + duplicates if student signs twice). Set = Voter list (one person, one vote, no duplicate). Map = Dictionary (word → meaning). Queue = Ticket counter line (first come, first served). Deque = Double-door lift (enter/exit from both ends).

2.2 Complete Program — All Interfaces in One Place

import java.util.*;
public class HierarchyComplete {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("A", "A", "B")); // duplicates OK
        Set<String> set = new HashSet<>(List.of("A", "A", "B"));     // duplicates removed
        Queue<String> queue = new ArrayDeque<>(List.of("First", "Second"));
        Deque<String> deque = new ArrayDeque<>(List.of("Middle"));
        Map<String, Integer> map = new HashMap<>(Map.of("A", 1, "B", 2));

        System.out.println("List (duplicates): " + list); // [A, A, B]
        System.out.println("Set (unique): " + set);       // [A, B]
        System.out.println("Queue poll (FIFO): " + queue.poll()); // First
        deque.addFirst("Front"); deque.addLast("Back");
        System.out.println("Deque: " + deque); // [Front, Middle, Back]
        System.out.println("Map get A: " + map.get("A")); // 1
        // Common methods: size(), isEmpty(), contains(), clear(), iterator()
    }
}
Chapter 3 • Intermediate • List Deep Dive

List: ArrayList vs LinkedList vs Vector vs CopyOnWriteArrayList

Most asked List question: “ArrayList vs LinkedList — which to use?” The answer is not “ArrayList is always better.” It depends on operation.

3.1 ArrayList — Internal Working

Internal: Dynamic array (Object[] elementData). Default capacity 10. When full, grows to 1.5x (old + old/2). New array created, old elements copied.

Time Complexity:

OperationArrayListWhy?
get(i)O(1)Direct index: arr[i]
add (end)O(1) amortizedAppend, grow rarely
add (middle)O(n)Shift elements right
remove (middle)O(n)Shift elements left
contains / searchO(n)Linear scan

3.2 LinkedList — Internal Working

Internal: Doubly Linked List. Each node has prev + data + next. No array, no resizing. Implements both List and Deque.

OperationLinkedListWhy?
get(i)O(n)Walk from head/tail to i
addFirst / addLastO(1)Just change pointers
add (middle)O(n)Walk to position, then O(1) link
removeFirst / LastO(1)Pointer change
Interview Line: “Use ArrayList when you need random access + mostly add at end (95% of cases). Use LinkedList only when you need frequent add/remove at both ends (Deque) — e.g., queue, undo stack. For middle insert/delete, both are O(n), ArrayList is usually faster due to cache locality.”

3.3 Complete Program — ArrayList vs LinkedList Performance (Run It)

import java.util.*;
public class ListPerformanceComplete {
    public static void main(String[] args) {
        int N = 100000;
        List<Integer> arrayList = new ArrayList<>();
        List<Integer> linkedList = new LinkedList<>();
        for (int i = 0; i < N; i++) { arrayList.add(i); linkedList.add(i); }

        // 1) Random access — ArrayList wins big
        long start = System.nanoTime();
        for (int i = 0; i < 10000; i++) arrayList.get(N / 2);
        System.out.println("ArrayList get(50000) x10000: " + (System.nanoTime() - start) / 1_000_000 + " ms");

        start = System.nanoTime();
        for (int i = 0; i < 10000; i++) linkedList.get(N / 2);
        System.out.println("LinkedList get(50000) x10000: " + (System.nanoTime() - start) / 1_000_000 + " ms");

        // 2) Add at beginning — LinkedList wins
        start = System.nanoTime();
        for (int i = 0; i < 1000; i++) arrayList.add(0, i); // shifts 100k elements each time!
        System.out.println("ArrayList add(0) x1000: " + (System.nanoTime() - start) / 1_000_000 + " ms");

        start = System.nanoTime();
        for (int i = 0; i < 1000; i++) linkedList.add(0, i); // just pointer change
        System.out.println("LinkedList add(0) x1000: " + (System.nanoTime() - start) / 1_000_000 + " ms");
    }
}

3.4 Vector vs ArrayList vs CopyOnWriteArrayList

Thread-Safe?GrowthWhen to Use
ArrayListNo1.5xSingle thread, 95% cases
VectorYes (synchronized, slow)2xLegacy — DO NOT use, use ArrayList + sync or CopyOnWrite
CopyOnWriteArrayListYes (lock-free read)Copy whole array on writeRead-heavy, write-rare: listeners, config
import java.util.concurrent.*;
public class CopyOnWriteComplete {
    public static void main(String[] args) throws Exception {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(List.of("A", "B"));
        // Reader iterates — no lock, no ConcurrentModificationException
        for (String s : list) { System.out.println("Reading: " + s); list.add("C"); } // safe!
        System.out.println("After: " + list);
        System.out.println("Rule: Write copies whole array — expensive if writes are frequent. Use only for read-heavy.");
    }
}
🌍 Real-Time: E-commerce cart = ArrayList (add at end, random access by index). Browser history / Undo = LinkedList / ArrayDeque (add/remove at ends). Live chat listeners = CopyOnWriteArrayList (many readers, few writers).

⭐ LeetCode 1 — Two Sum (ArrayList + HashMap Pattern)

Problem: Given [2,7,11,15], target 9, return indices [0,1].

Easy: Two loops O(n²). Optimized: One pass with HashMap O(n) — for each number, check if target - num already in map.

import java.util.*;
public class TwoSum {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>(); // value → index
        for (int i = 0; i < nums.length; i++) {
            int need = target - nums[i];
            if (map.containsKey(need)) return new int[]{map.get(need), i};
            map.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new TwoSum().twoSum(new int[]{2,7,11,15}, 9))); // [0,1]
    }
}
Chapter 4 • Intermediate • Set

Set: HashSet vs LinkedHashSet vs TreeSet

Set = No duplicates. But which Set? Depends on whether you need order, sorting, or just uniqueness.

SetInternalOrderNull?get / addUse When
HashSetHashMap (value = dummy)No order1 null OKO(1)Just uniqueness, fastest
LinkedHashSetLinkedHashMapInsertion order1 null OKO(1)Uniqueness + insertion order
TreeSetTreeMap (Red-Black Tree)Sorted orderNo nullO(log n)Uniqueness + sorted
EnumSetBit vectorEnum orderNo nullO(1)Set of enum values, fastest
Surprise Fact: HashSet internally uses HashMap! HashSet.add(x) = map.put(x, PRESENT) where PRESENT is a dummy object. That is why HashSet has same O(1) and same hashCode rules as HashMap.

4.1 Complete Program — All Sets Side-by-Side

import java.util.*;
public class SetComplete {
    public static void main(String[] args) {
        Set<String> hashSet = new HashSet<>();
        Set<String> linkedSet = new LinkedHashSet<>();
        Set<String> treeSet = new TreeSet<>();
        String[] words = {"Banana", "Apple", "Mango", "Apple", "Banana"};
        for (String w : words) { hashSet.add(w); linkedSet.add(w); treeSet.add(w); }
        System.out.println("HashSet (no order): " + hashSet); // [Apple, Banana, Mango] any order
        System.out.println("LinkedHashSet (insertion): " + linkedSet); // [Banana, Apple, Mango]
        System.out.println("TreeSet (sorted): " + treeSet); // [Apple, Banana, Mango]
        // Useful Set operations
        Set<Integer> a = new HashSet<>(Set.of(1,2,3,4));
        Set<Integer> b = new HashSet<>(Set.of(3,4,5,6));
        Set<Integer> union = new HashSet<>(a); union.addAll(b); // {1,2,3,4,5,6}
        Set<Integer> inter = new HashSet<>(a); inter.retainAll(b); // {3,4}
        Set<Integer> diff = new HashSet<>(a); diff.removeAll(b); // {1,2}
        System.out.println("Union=" + union + " Intersection=" + inter + " Diff=" + diff);
    }
}
🌍 Real-Time: Unique visitor IDs = HashSet. Unique tags in insertion order (Instagram hashtags) = LinkedHashSet. Leaderboard sorted scores = TreeSet. Days of week selected = EnumSet.

⭐ LeetCode 217 — Contains Duplicate EASY

Problem: Given array, return true if any value appears twice.

import java.util.*;
public class ContainsDuplicate {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        for (int n : nums) {
            if (!seen.add(n)) return true; // add returns false if already present
            // seen.add() is O(1) — better than contains() + add() (2 lookups)
        }
        return false;
    }
    public static void main(String[] args) {
        System.out.println(new ContainsDuplicate().containsDuplicate(new int[]{1,2,3,1})); // true
    }
}

Interview tip: Use add() return value — it already tells you if duplicate. Do not do contains() then add() (2 hashes).

⭐ LeetCode 128 — Longest Consecutive Sequence MEDIUM

Problem: Given [100,4,200,1,3,2], longest consecutive = [1,2,3,4] length 4. Must be O(n).

import java.util.*;
public class LongestConsecutive {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int n : nums) set.add(n);
        int longest = 0;
        for (int n : set) {
            if (!set.contains(n - 1)) { // only start counting from sequence start
                int curr = n, len = 1;
                while (set.contains(curr + 1)) { curr++; len++; }
                longest = Math.max(longest, len);
            }
        }
        return longest;
    }
    public static void main(String[] args) {
        System.out.println(new LongestConsecutive().longestConsecutive(new int[]{100,4,200,1,3,2})); // 4
    }
}

Why O(n)? Each number is visited at most twice — once as start check, once in while loop. Without the !contains(n-1) check, it would be O(n²).

Chapter 5 • Intermediate to Advanced • Map Internals

Map: HashMap Internals, LinkedHashMap, TreeMap, WeakHashMap

HashMap is the most asked topic in Java interviews. If you can explain its internals, you can crack any Map question.

5.1 HashMap — Internal Working (Step-by-Step)

  1. Hash: key.hashCode() → spread function (h ^ (h >>> 16)) to mix high bits.
  2. Index: index = hash & (capacity - 1). Capacity is power of 2 (16, 32, 64) so & works like % but faster.
  3. Bucket: Array of buckets. Each bucket is LinkedList (Java 7) or LinkedList → Tree (Java 8+).
  4. Collision: Two keys same index → chain in same bucket. Java 8: if chain length > 8 and capacity >= 64, convert to Red-Black Tree (O(log n) instead of O(n)).
  5. Resize: When size > capacity * loadFactor (0.75), double capacity, rehash all entries. Default: 16 → 32 → 64.
HashMap Visual (capacity 16):
Bucket 0: null
Bucket 1: [KeyA → Val] → [KeyB → Val]  // collision: A and B same index
Bucket 2: [KeyC → Val]
...
Bucket 15: null
// get(KeyB): hash → index 1 → walk chain → equals() match → return Val
🏫 Non-Tech Analogy: HashMap = School with 16 classrooms. Student’s roll number decides classroom: roll % 16. If two students get same classroom, they sit in a row (chain). If row gets too long (>8), teacher makes a sorted tree to find students faster. If school fills 75%, build a bigger school (resize) and reassign classrooms.

5.2 Complete Program — HashMap Behaviour + Collision Demo

import java.util.*;
public class HashMapComplete {
    // Custom key with BAD hashCode — all keys go to same bucket → O(n)
    static class BadKey {
        String name;
        BadKey(String n) { name = n; }
        public int hashCode() { return 1; } // BAD: all same bucket
        public boolean equals(Object o) { return o instanceof BadKey && ((BadKey)o).name.equals(name); }
        public String toString() { return name; }
    }
    // Custom key with GOOD hashCode — distributed
    static class GoodKey {
        String name;
        GoodKey(String n) { name = n; }
        public int hashCode() { return Objects.hash(name); } // GOOD: distributed
        public boolean equals(Object o) { return o instanceof GoodKey && ((GoodKey)o).name.equals(name); }
        public String toString() { return name; }
    }
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1); map.put("B", 2); map.put("A", 10); // duplicate key overwrites
        System.out.println("Map: " + map); // {A=10, B=2} — key A updated, not duplicated
        System.out.println("Get A: " + map.get("A"));
        System.out.println("GetOrDefault X: " + map.getOrDefault("X", -1));
        System.out.println("Contains Key B? " + map.containsKey("B"));
        // computeIfAbsent — only one thread loads from DB (cache pattern)
        Map<String, String> cache = new HashMap<>();
        String val = cache.computeIfAbsent("user:101", k -> "DB-User-" + k);
        System.out.println("Cache: " + val);
        // merge — word count in one line
        Map<String, Integer> wordCount = new HashMap<>();
        for (String w : "apple banana apple mango apple".split(" ")) wordCount.merge(w, 1, Integer::sum);
        System.out.println("WordCount: " + wordCount); // {apple=3, banana=1, mango=1}
    }
}

5.3 HashMap vs LinkedHashMap vs TreeMap vs Hashtable vs ConcurrentHashMap

MapOrderNull Key?Thread-Safe?get/putUse When
HashMapNo1 null key OKNoO(1)General, fastest, single thread
LinkedHashMapInsertion / Access order1 null OKNoO(1)LRU Cache, insertion order
TreeMapSorted by keyNo null keyNoO(log n)Sorted keys, range queries
HashtableNoNo nullYes (slow)O(1)Legacy — DO NOT use
ConcurrentHashMapNoNo nullYes (fast)O(1)Multi-threaded, production
WeakHashMapNo1 null OKNoO(1)Cache where key can be GC'd

5.4 LinkedHashMap — LRU Cache in 5 Lines

import java.util.*;
public class LRUComplete {
    static class LRUCache<K,V> extends LinkedHashMap<K,V> {
        private final int capacity;
        LRUCache(int cap) { super(cap, 0.75f, true); capacity = cap; } // true = access-order
        protected boolean removeEldestEntry(Map.Entry<K,V> e) { return size() > capacity; }
    }
    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(3);
        cache.put(1, "A"); cache.put(2, "B"); cache.put(3, "C");
        System.out.println(cache); // {1=A, 2=B, 3=C}
        cache.get(1); // 1 becomes most recent
        cache.put(4, "D"); // 2 is LRU, evicted
        System.out.println(cache); // {3=C, 1=A, 4=D} — 2 evicted
    }
}

5.5 TreeMap — Sorted + Range Queries

import java.util.*;
public class TreeMapComplete {
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>();
        map.put(10, "Ten"); map.put(5, "Five"); map.put(20, "Twenty"); map.put(15, "Fifteen");
        System.out.println("Sorted: " + map); // {5, 10, 15, 20}
        System.out.println("First: " + map.firstKey() + " Last: " + map.lastKey());
        System.out.println("Floor 12 (≤12): " + map.floorKey(12)); // 10
        System.out.println("Ceiling 12 (≥12): " + map.ceilingKey(12)); // 15
        System.out.println("SubMap 10-20: " + map.subMap(10, 20)); // {10, 15}
        System.out.println("HeadMap <15: " + map.headMap(15)); // {5, 10}
        // Real-time: Leaderboard, time-series (timestamp → event), price ranges
    }
}
🧑‍🏫 Expert Note — HashMap Resizing & Treeify: Initial capacity 16, load factor 0.75 → resize at 12 entries. Treeify threshold 8, untreeify threshold 6, min treeify capacity 64. Why 8? Poisson distribution: probability of 8 collisions with good hash is ~0.00000006 — if it happens, it is likely a DoS attack with bad hash, so tree protects you. This is a Senior-level answer.

⭐ LeetCode 49 — Group Anagrams MEDIUM

Problem: Group ["eat","tea","tan","ate","nat","bat"] → [["eat","tea","ate"],["tan","nat"],["bat"]].

import java.util.*;
public class GroupAnagrams {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String s : strs) {
            char[] chars = s.toCharArray();
            Arrays.sort(chars); // sorted chars = key: "aet" for eat/tea/ate
            String key = new String(chars);
            map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
        }
        return new ArrayList<>(map.values());
    }
    public static void main(String[] args) {
        System.out.println(new GroupAnagrams().groupAnagrams(new String[]{"eat","tea","tan","ate","nat","bat"}));
    }
}

⭐ LeetCode 146 — LRU Cache MEDIUM • Most Asked

Problem: Design LRU Cache with get() and put() in O(1). See LRU code above (LinkedHashMap version). Interview twist: “Implement without LinkedHashMap?” → Use HashMap + Doubly Linked List: HashMap for O(1) lookup, DLL for O(1) move-to-head + remove-tail. See Multithreading tutorial Ch 10 for full DLL version.

⭐ LeetCode 347 — Top K Frequent Elements MEDIUM

import java.util.*;
public class TopKFrequent {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int n : nums) freq.merge(n, 1, Integer::sum);
        // Min-heap of size k: smallest freq at top, evict when > k
        PriorityQueue<Map.Entry<Integer, Integer>> heap =
            new PriorityQueue<>(Map.Entry.comparingByValue());
        for (var e : freq.entrySet()) { heap.offer(e); if (heap.size() > k) heap.poll(); }
        int[] res = new int[k];
        for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();
        return res;
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new TopKFrequent().topKFrequent(new int[]{1,1,1,2,2,3}, 2))); // [1,2]
    }
}
Chapter 6 • Intermediate • Queue & Deque

Queue, Deque, PriorityQueue, Stack

Queue = FIFO. Deque = Both ends. PriorityQueue = By priority, not FIFO. Stack = LIFO. Choosing wrong one is a common interview mistake.

StructureOrderBest ClassUse When
Queue (FIFO)First in, first outArrayDeque / LinkedListTask queue, print queue, BFS
DequeBoth endsArrayDequeUndo, sliding window, palindrome
PriorityQueueBy priority (min-heap)PriorityQueueTop K, Dijkstra, scheduling
Stack (LIFO)Last in, first outArrayDeque (NOT Stack class)Undo, expression, DFS, parentheses
Do NOT use Stack class: It is legacy, synchronized, extends Vector (slow). Use ArrayDeque as Stack: push(), pop(), peek(). Interviewers check this.

6.1 Complete Program — Queue vs Deque vs PriorityQueue vs Stack

import java.util.*;
public class QueueDequeComplete {
    public static void main(String[] args) {
        // QUEUE: FIFO
        Queue<String> queue = new ArrayDeque<>();
        queue.offer("First"); queue.offer("Second"); queue.offer("Third");
        System.out.println("Queue poll: " + queue.poll()); // First
        System.out.println("Queue peek: " + queue.peek()); // Second

        // DEQUE: both ends
        Deque<String> deque = new ArrayDeque<>();
        deque.addFirst("Front"); deque.addLast("Back");
        System.out.println("Deque: " + deque); // [Front, Back]
        System.out.println("Deque pollFirst: " + deque.pollFirst()); // Front

        // PRIORITY QUEUE: min-heap, smallest first
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.offer(30); pq.offer(10); pq.offer(20);
        System.out.println("PQ poll order: " + pq.poll() + ", " + pq.poll() + ", " + pq.poll()); // 10,20,30

        // Max-heap: reverse order
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
        maxHeap.offer(10); maxHeap.offer(30); maxHeap.offer(20);
        System.out.println("MaxHeap poll: " + maxHeap.poll()); // 30

        // STACK via ArrayDeque: LIFO
        Deque<String> stack = new ArrayDeque<>();
        stack.push("A"); stack.push("B"); stack.push("C");
        System.out.println("Stack pop: " + stack.pop()); // C (last in, first out)
        System.out.println("Stack peek: " + stack.peek()); // B
    }
}

6.2 Queue Methods — offer vs add, poll vs remove, peek vs element

OperationReturns special value (safe)Throws exception
Addoffer() → false if fulladd() → IllegalStateException
Removepoll() → null if emptyremove() → NoSuchElementException
Examinepeek() → null if emptyelement() → NoSuchElementException

Interview tip: Always use offer / poll / peek (safe) in production, not add / remove / element (throws).

⭐ LeetCode 20 — Valid Parentheses EASY • Stack

import java.util.*;
public class ValidParentheses {
    public boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>(); // use Deque as Stack
        Map<Character, Character> pairs = Map.of(')', '(', '}', '{', ']', '[');
        for (char c : s.toCharArray()) {
            if (pairs.containsValue(c)) stack.push(c);
            else if (stack.isEmpty() || stack.pop() != pairs.get(c)) return false;
        }
        return stack.isEmpty();
    }
    public static void main(String[] args) {
        System.out.println(new ValidParentheses().isValid("()[]{}")); // true
        System.out.println(new ValidParentheses().isValid("(]")); // false
    }
}

⭐ LeetCode 239 — Sliding Window Maximum HARD • Deque

Problem: [1,3,-1,-3,5,3,6,7], k=3 → [3,3,5,5,6,7]. Naive O(n*k) too slow. Deque gives O(n).

import java.util.*;
public class SlidingWindowMax {
    public int[] maxSlidingWindow(int[] nums, int k) {
        Deque<Integer> deque = new ArrayDeque<>(); // stores indices, decreasing values
        int[] res = new int[nums.length - k + 1];
        for (int i = 0; i < nums.length; i++) {
            // Remove indices out of window
            if (!deque.isEmpty() && deque.peekFirst() <= i - k) deque.pollFirst();
            // Remove smaller values — they can never be max
            while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) deque.pollLast();
            deque.offerLast(i);
            if (i >= k - 1) res[i - k + 1] = nums[deque.peekFirst()];
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new SlidingWindowMax().maxSlidingWindow(new int[]{1,3,-1,-3,5,3,6,7}, 3)));
    }
}

⭐ LeetCode 215 — Kth Largest Element MEDIUM • PriorityQueue

import java.util.*;
public class KthLargest {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // size k, smallest at top
        for (int n : nums) { minHeap.offer(n); if (minHeap.size() > k) minHeap.poll(); }
        return minHeap.peek(); // kth largest = smallest in top-k heap
    }
    public static void main(String[] args) {
        System.out.println(new KthLargest().findKthLargest(new int[]{3,2,1,5,6,4}, 2)); // 5
    }
}
Chapter 7 • Intermediate • #1 Trap

equals() & hashCode() Contract — The #1 Interview Trap

If you get this wrong, HashMap / HashSet will silently fail — duplicate objects, lost entries, wrong contains().

7.1 Contract — 3 Rules (Memorize)

  1. If a.equals(b) is true, then a.hashCode() == b.hashCode() MUST be true.
  2. If a.hashCode() == b.hashCode(), then a.equals(b) MAY be false (collision allowed).
  3. If you override equals(), you MUST override hashCode() — and vice versa. If you override only one, HashMap breaks.

7.2 Problem — Broken equals/hashCode (Run It, See Bug)

import java.util.*;
public class EqualsHashCodeBroken {
    // WRONG: equals overridden, hashCode NOT overridden — uses Object.hashCode (memory address)
    static class UserBroken {
        String id;
        UserBroken(String id) { this.id = id; }
        public boolean equals(Object o) { return o instanceof UserBroken && ((UserBroken)o).id.equals(id); }
        // hashCode NOT overridden — BUG!
    }
    // CORRECT: both overridden, using same fields
    static class UserCorrect {
        String id;
        UserCorrect(String id) { this.id = id; }
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof UserCorrect)) return false;
            return Objects.equals(id, ((UserCorrect)o).id);
        }
        public int hashCode() { return Objects.hash(id); } // same field as equals
    }
    public static void main(String[] args) {
        // BROKEN: two equal users, different hashCodes → HashMap treats as different keys
        Map<UserBroken, String> brokenMap = new HashMap<>();
        brokenMap.put(new UserBroken("101"), "Dharmendra");
        System.out.println("Broken get (should be Dharmendra): " + brokenMap.get(new UserBroken("101"))); // null — BUG!

        // CORRECT: same hashCode → same bucket → equals match → found
        Map<UserCorrect, String> correctMap = new HashMap<>();
        correctMap.put(new UserCorrect("101"), "Dharmendra");
        System.out.println("Correct get: " + correctMap.get(new UserCorrect("101"))); // Dharmendra

        Set<UserCorrect> set = new HashSet<>();
        set.add(new UserCorrect("101")); set.add(new UserCorrect("101"));
        System.out.println("Set size (should be 1): " + set.size());
    }
}

7.3 Rules for Good equals/hashCode

// BEST: Java Record — equals, hashCode, toString auto-generated, immutable
record UserRecord(String id, String name) {}
// Usage: Map<UserRecord, String> map = new HashMap<>();
// map.put(new UserRecord("101", "Dharmendra"), "Data"); // works correctly, no manual code
🗣 Interview Q: What happens if you override equals but not hashCode? Answer: “Two equal objects will have different hashCodes (Object’s address-based). HashMap puts them in different buckets, so get() returns null, Set allows duplicates. That violates the contract.”
🌍 Real-Time: User object as HashMap key, Product as cache key, Employee in HashSet for deduplication — all break if equals/hashCode is wrong. This bug is silent — no exception, just wrong data.
Chapter 8 • Intermediate • Sorting

Sorting, Comparable vs Comparator, Collections Utility

8.1 Comparable vs Comparator — When to Use Which?

ComparableComparator
MethodcompareTo()compare()
Where?Inside class itselfSeparate class / lambda
How many orderings?One — natural orderingMany — by name, age, salary, etc.
Packagejava.langjava.util
ExampleString, Integer implement ComparableComparator.comparing(User::getAge)

8.2 Complete Program — Comparable + Comparator + Sorting

import java.util.*;
public class SortingComplete {
    static class Student implements Comparable<Student> {
        String name; int age; int marks;
        Student(String n, int a, int m) { name = n; age = a; marks = m; }
        // Natural ordering: by marks (ascending)
        public int compareTo(Student other) { return Integer.compare(this.marks, other.marks); }
        public String toString() { return name + "(" + marks + ")"; }
    }
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>(List.of(
            new Student("Asha", 20, 85), new Student("Ravi", 22, 90), new Student("Meena", 19, 75)));
        // 1) Natural ordering (Comparable): by marks
        Collections.sort(list);
        System.out.println("By marks: " + list); // Meena(75), Asha(85), Ravi(90)

        // 2) Comparator: by name
        list.sort(Comparator.comparing(s -> s.name));
        System.out.println("By name: " + list);

        // 3) Comparator: by age descending, then by name
        list.sort(Comparator.comparingInt((Student s) -> s.age).reversed().thenComparing(s -> s.name));
        System.out.println("By age desc: " + list);

        // 4) Modern: Stream sorting
        List<Student> top = list.stream().sorted(Comparator.comparingInt((Student s) -> s.marks).reversed()).limit(2).toList();
        System.out.println("Top 2 by marks: " + top);

        // 5) Collections utility: binarySearch (list MUST be sorted)
        List<Integer> nums = new ArrayList<>(List.of(10, 20, 30, 40));
        System.out.println("binarySearch 30: index " + Collections.binarySearch(nums, 30)); // 2
        System.out.println("Max: " + Collections.max(nums) + " Min: " + Collections.min(nums));
        Collections.reverse(nums); System.out.println("Reversed: " + nums);
        Collections.shuffle(nums); System.out.println("Shuffled: " + nums);
    }
}

8.3 Sorting Gotchas

🗣 Interview Q: Comparable vs Comparator? Answer: “Comparable is natural ordering, one per class, inside class. Comparator is custom ordering, many per class, outside class. Use Comparable for default, Comparator for alternative orderings.”
Chapter 9 • Advanced • Concurrency + Streams

Concurrent Collections, Fail-Fast vs Fail-Safe, Streams

9.1 Fail-Fast vs Fail-Safe — Most Asked in Interviews

Fail-FastFail-Safe
ExamplesArrayList, HashMap, HashSetConcurrentHashMap, CopyOnWriteArrayList
What happens on modify during iteration?ConcurrentModificationExceptionNo exception, works on snapshot / weakly consistent
How?modCount check — if modCount changes during iteration, throwCopy / segment lock — iterator sees old snapshot

9.2 Complete Program — Fail-Fast Bug + 3 Fixes

import java.util.*;
import java.util.concurrent.*;
public class FailFastComplete {
    public static void main(String[] args) {
        // BUG: Fail-Fast — ConcurrentModificationException
        List<String> list = new ArrayList<>(List.of("A", "B", "C"));
        try {
            for (String s : list) { if (s.equals("B")) list.remove(s); } // throws!
        } catch (ConcurrentModificationException e) {
            System.out.println("Fail-Fast: ConcurrentModificationException as expected");
        }
        // FIX 1: Iterator.remove() — allowed
        List<String> list2 = new ArrayList<>(List.of("A", "B", "C"));
        Iterator<String> it = list2.iterator();
        while (it.hasNext()) { if (it.next().equals("B")) it.remove(); }
        System.out.println("Fix1 Iterator.remove: " + list2); // [A, C]

        // FIX 2: removeIf (Java 8+) — cleanest
        List<String> list3 = new ArrayList<>(List.of("A", "B", "C"));
        list3.removeIf(s -> s.equals("B"));
        System.out.println("Fix2 removeIf: " + list3);

        // FIX 3: Fail-Safe collection — CopyOnWriteArrayList, no exception
        CopyOnWriteArrayList<String> cow = new CopyOnWriteArrayList<>(List.of("A", "B", "C"));
        for (String s : cow) { if (s.equals("B")) cow.remove(s); } // no exception, iterates snapshot
        System.out.println("Fix3 CopyOnWrite: " + cow);

        // ConcurrentHashMap — Fail-Safe, no exception, weakly consistent
        ConcurrentHashMap<String, Integer> cmap = new ConcurrentHashMap<>(Map.of("A", 1, "B", 2));
        for (var e : cmap.entrySet()) { cmap.put("C", 3); } // no exception
        System.out.println("ConcurrentHashMap: " + cmap);
    }
}

9.3 ConcurrentHashMap — How It Works (Short Theory)

Old (Java 7): Segmented locks — 16 segments, each with its own lock. Threads writing to different segments do not block each other.

New (Java 8+): CAS + synchronized on bucket (first node). Read is lock-free. Write locks only one bucket, not whole map. That is why it is much faster than Hashtable (which locks whole map).

Key rules: No null key / value (throws NPE). computeIfAbsent is atomic. size() is approximate (not exact) under concurrency — use mappingCount().

import java.util.concurrent.*;
public class ConcurrentMapComplete {
    public static void main(String[] args) throws Exception {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        // 10 threads increment same key 1000 times — should be 10000
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) map.merge("visits", 1, Integer::sum);
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        System.out.println("Visits = " + map.get("visits")); // Always 10000, thread-safe
        // Hashtable would also be thread-safe but much slower (whole map lock)
    }
}

9.4 Streams — Modern Collection Processing

Problem: Filter, map, sort, collect — with loops it is 15 lines. With Streams, 3 lines, readable, parallelizable.

import java.util.*;
import java.util.stream.*;
public class StreamsComplete {
    record Student(String name, int marks, String city) {}
    public static void main(String[] args) {
        List<Student> students = List.of(
            new Student("Asha", 90, "Mumbai"), new Student("Ravi", 70, "Delhi"),
            new Student("Meena", 95, "Mumbai"), new Student("Arjun", 60, "Delhi"));

        // 1) Filter + Map + Collect: names of Mumbai students with marks > 80
        List<String> names = students.stream()
            .filter(s -> s.city().equals("Mumbai") && s.marks() > 80)
            .map(Student::name)
            .sorted()
            .toList();
        System.out.println("Mumbai toppers: " + names); // [Asha, Meena]

        // 2) Grouping: city → list of students
        Map<String, List<Student>> byCity = students.stream().collect(Collectors.groupingBy(Student::city));
        System.out.println("By city: " + byCity);

        // 3) Counting / Averaging: average marks per city
        Map<String, Double> avgByCity = students.stream()
            .collect(Collectors.groupingBy(Student::city, Collectors.averagingInt(Student::marks)));
        System.out.println("Avg by city: " + avgByCity);

        // 4) Max / Min: topper
        students.stream().max(Comparator.comparingInt(Student::marks)).ifPresent(s -> System.out.println("Topper: " + s));

        // 5) Parallel stream: for large lists, use parallel() — uses ForkJoinPool
        List<Integer> big = IntStream.rangeClosed(1, 1000000).boxed().toList();
        long sum = big.parallelStream().mapToLong(Integer::longValue).sum();
        System.out.println("Parallel sum: " + sum);

        // 6) Common mistake: Stream can be used only once!
        Stream<String> stream = Stream.of("A", "B");
        stream.forEach(System.out::println);
        // stream.forEach(System.out::println); // IllegalStateException — stream already consumed!
        System.out.println("Rule: Stream is single-use. Create new stream for each operation.");
    }
}
🧑‍🏫 Expert Note — When NOT to use parallelStream(): Small lists (<10k), I/O work (DB calls — blocks ForkJoinPool), or order-sensitive work. Parallel stream uses common ForkJoinPool (cores-1 threads). For I/O, use custom Executor + CompletableFuture instead. This is a Senior answer.
Chapter 10 • Advanced • Real Systems + LeetCode Patterns

Real-Time Systems, LeetCode Patterns & Interview Plan

10.1 Real-Time System Design — Which Collection for Which Problem?

Real ProblemCollection to UseWhy?
Word frequency, user visitsHashMap + merge()O(1) count, one line
Unique visitorsHashSetO(1) duplicate check
Leaderboard, sorted scoresTreeSet / TreeMapSorted, O(log n)
LRU CacheLinkedHashMap (access-order)O(1) get/put + eviction
Task queue, BFSArrayDeque (Queue)O(1) offer/poll
Undo / Redo, parenthesesArrayDeque (Stack)O(1) push/pop
Top K, schedulingPriorityQueue (Heap)O(log n) insert, O(1) peek
Sliding window maxArrayDeque (Monotonic)O(n) instead of O(n*k)
Multi-threaded cacheConcurrentHashMapThread-safe, fast, no whole-map lock
Read-heavy listenersCopyOnWriteArrayListLock-free read, no CME

10.2 LeetCode Patterns — The 6 Patterns That Solve 80% of Collection Problems

PatternCollectionLeetCode Examples
HashMap for O(1) lookupHashMapTwo Sum (1), Group Anagrams (49), Isomorphic Strings (205)
HashSet for duplicate / seenHashSetContains Duplicate (217), Longest Consecutive (128), Happy Number (202)
Two Pointers + ListArrayList / Array3Sum (15), Container With Most Water (11), Remove Duplicates (26)
Stack for matching / monotonicArrayDequeValid Parentheses (20), Daily Temperatures (739), Largest Rectangle (84)
Heap for Top KPriorityQueueKth Largest (215), Top K Frequent (347), Merge K Sorted Lists (23)
Deque for sliding windowArrayDequeSliding Window Max (239), First Negative in Window

⭐ LeetCode 3 — Longest Substring Without Repeating Characters MEDIUM • HashMap + Sliding Window

import java.util.*;
public class LongestSubstring {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> lastSeen = new HashMap<>(); // char → last index
        int max = 0, start = 0;
        for (int end = 0; end < s.length(); end++) {
            char c = s.charAt(end);
            if (lastSeen.containsKey(c)) start = Math.max(start, lastSeen.get(c) + 1);
            lastSeen.put(c, end);
            max = Math.max(max, end - start + 1);
        }
        return max;
    }
    public static void main(String[] args) {
        System.out.println(new LongestSubstring().lengthOfLongestSubstring("abcabcbb")); // 3 (abc)
        System.out.println(new LongestSubstring().lengthOfLongestSubstring("bbbbb")); // 1 (b)
    }
}

Pattern: Sliding window + HashMap for last seen index. O(n), one pass. This pattern also solves: Minimum Window Substring (76), Longest Repeating Character Replacement (424).

⭐ LeetCode 15 — 3Sum MEDIUM • Sorting + Two Pointers

import java.util.*;
public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums); // sort first — O(n log n)
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i-1]) continue; // skip duplicate i
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    res.add(List.of(nums[i], nums[left], nums[right]));
                    while (left < right && nums[left] == nums[left+1]) left++;
                    while (left < right && nums[right] == nums[right-1]) right--;
                    left++; right--;
                } else if (sum < 0) left++; else right--;
            }
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(new ThreeSum().threeSum(new int[]{-1,0,1,2,-1,-4})); // [[-1,-1,2],[-1,0,1]]
    }
}

⭐ LeetCode 23 — Merge K Sorted Lists HARD • PriorityQueue

import java.util.*;
public class MergeKLists {
    static class ListNode { int val; ListNode next; ListNode(int v) { val = v; } }
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> heap = new PriorityQueue<>(Comparator.comparingInt(n -> n.val));
        for (ListNode n : lists) if (n != null) heap.offer(n);
        ListNode dummy = new ListNode(0), curr = dummy;
        while (!heap.isEmpty()) {
            ListNode smallest = heap.poll();
            curr.next = smallest; curr = curr.next;
            if (smallest.next != null) heap.offer(smallest.next);
        }
        return dummy.next;
    }
    public static void main(String[] args) {
        System.out.println("Merge K Lists: Heap always gives smallest head — O(N log K).");
    }
}

10.3 Common Mistakes Interviewers Catch

10.4 Rapid-Fire Revision — Speak in 10 Seconds Each

QuestionOne-Line Answer
ArrayList vs LinkedList?ArrayList: O(1) get, good for random access. LinkedList: O(1) add/remove at ends.
HashMap vs TreeMap?HashMap: O(1), no order. TreeMap: O(log n), sorted.
HashSet internal?HashMap with dummy value.
equals + hashCode?If equals true, hashCode must be equal. Override both together.
Fail-Fast vs Fail-Safe?Fail-Fast throws CME. Fail-Safe uses snapshot / concurrent, no exception.
Comparable vs Comparator?Comparable: natural, inside class. Comparator: custom, outside class.
Queue offer vs add?offer returns false if full. add throws exception.
PriorityQueue order?Min-heap by default. Smallest first.
ConcurrentHashMap vs Hashtable?CHM locks one bucket, fast. Hashtable locks whole map, slow. CHM: no nulls.
When to use Deque?Both ends: sliding window, undo, palindrome, BFS.

10.5 7-Day Practice Plan

Day 1: List + Set
Day 2: Map + HashMap internals
Day 3: equals/hashCode + Sorting
Day 4: Queue + Deque + PriorityQueue
Day 5: LeetCode: Two Sum, Valid Parentheses, Group Anagrams
Day 6: LeetCode: 3Sum, Top K, Sliding Window
Day 7: Mock — 1 DSA + 1 Internals + 10 Rapid-Fire
Final Interview Tip: After solving any collection problem, always say: “Time complexity is O(...), Space is O(...), Edge cases: empty input, single element, duplicates, null.” Interviewers note this.

❓ Q&A — Questions Students Ask

Q: Why is HashMap not thread-safe?
A: Two threads putting at same time can corrupt bucket chain or lose entries during resize. Use ConcurrentHashMap for multi-threaded code.

Q: Can HashMap have null key?
A: Yes, one null key (stored in bucket 0). HashSet can have one null. TreeMap cannot have null key (needs comparison), ConcurrentHashMap cannot have null key/value (throws NPE).

Q: What is load factor 0.75?
A: Trade-off between time and space. Lower load factor = fewer collisions, more memory. Higher = more collisions, less memory. 0.75 is the sweet spot found by research.

Q: ArrayList vs Array?
A: ArrayList is dynamic, has methods, uses generics, but only stores objects (autoboxing for primitives). Array is fixed, faster for primitives, no methods.

Q: What is unmodifiable collection?
A: List.copyOf() or Collections.unmodifiableList() — read-only view. Any add/remove throws UnsupportedOperationException. Use for returning safe copies from APIs.

⭐ Bonus — How to Choose Collection in 10 Seconds (Decision Tree)

Need Key → Value? ──YES──► Need sorted keys? ──YES──► TreeMap
  │                              └──NO──► Need thread-safe? ──YES──► ConcurrentHashMap
  │                                                └──NO──► HashMap (or LinkedHashMap for order)
  └──NO
Need unique only? ──YES──► Need sorted? ──YES──► TreeSet
  │                             └──NO──► Need insertion order? ──YES──► LinkedHashSet
  │                                               └──NO──► HashSet
  └──NO
Need FIFO / Priority? ──YES──► Need priority? ──YES──► PriorityQueue
  │                                    └──NO──► ArrayDeque as Queue
  └──NO
Need LIFO (Stack)? ──YES──► ArrayDeque as Stack
  └──NO──► Need index access? ──YES──► ArrayList
                  └──NO──► LinkedList / ArrayDeque
🧑‍💼 For Non-Tech Readers — One Paragraph Summary:
Collections are smart containers for data. List keeps order and allows duplicates (like a shopping list). Set keeps only unique items (like a voter list). Map links a key to a value (like a dictionary). Queue processes in order (like a ticket line). Good engineers don’t just store data — they choose the container that makes searching, sorting, and updating fastest. That choice can make an app 10x faster or 10x slower.