Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Collections, From the Inside

    Choosing the Right Collection

    Taught step by step, with real output.

    Chapter 11 of 112 min read

    The decision table:

    You need…UseKey costs
    a growable sequence, access by indexArrayListget O(1), add-at-end amortized O(1)
    look up by key, no order neededHashMapO(1) average
    "have I seen this?" / unique itemsHashSetO(1) average
    key look-up and insertion orderLinkedHashMap / LinkedHashSetO(1) average
    an LRU cacheLinkedHashMap(accessOrder = true) + removeEldestEntryO(1)
    keys sorted, floor/ceiling/range queriesTreeMap / TreeSetO(log n)
    a stack (LIFO)ArrayDeque (push/pop/peek)O(1)
    a queue (FIFO), BFSArrayDeque (offer/poll/peek)O(1)
    always get the min (or max) next; top-KPriorityQueueoffer/poll O(log n), peek O(1)
    counts of small integers or lettersint[] (e.g. new int[26])O(1), fastest of all
    keys are enum valuesEnumMap / EnumSetO(1), very fast
    shared between threadsConcurrentHashMap, BlockingQueue…Concurrency

    Rules of thumb for DSA:

    1. Default to ArrayList, HashMap, HashSet, ArrayDeque.

    2. Reach for TreeMap only when you need order or nearest-key questions, and PriorityQueue only when you repeatedly need the current min/max.

    3. When keys are small integers (0..n) or letters, a plain array beats any map.

    4. For a million-plus numbers, prefer primitive arrays over boxed collections (Classes, Objects and Memory Ch 8: 3 MB vs 21 MB).