Skip to content

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

    Java / Collections, From the Inside

    Quick Reference

    Glossary and cheat sheet for Collections, From the Inside — the page to reread before an interview.

    Extra: Reference6 min read

    Glossary#

    TermPlain meaningChapter
    Collections FrameworkJava's standard data-structure library1
    List / Set / Queue / Deque / Mapsequence / unique items / take from front / both ends / key→value1
    ArrayList / capacitygrowable array / current internal array size2
    LinkedList / nodedoubly linked list / one element + prev/next links2
    immutable vs fixed-sizeList.of (no changes) vs Arrays.asList (set OK, no add/remove)2
    Iterator / fail-fastwalker with hasNext/next/remove / throws on outside modification3
    ConcurrentModificationExceptioncollection changed during iteration3
    HashMap / bucket / tablehash-based map / one slot of the array / the array4
    hash spreadingh ^ (h >>> 16) before choosing a bucket4
    collision / chainingtwo keys, same bucket / a list per bucket4
    treeificationbucket list → red-black tree at 8 entries4
    load factor / resize / rehash0.75 fullness threshold / double the table / re-place entries4
    HashSeta HashMap with only keys5
    LinkedHashMap / access orderinsertion-ordered map / reads move entries to the end5
    LRU cacheevicts the least recently used entry5
    TreeMap / TreeSet / red-black treesorted map / sorted set / self-balancing BST inside6
    floor / ceiling / higher / lower≤ / ≥ / > / < nearest key6
    Comparable / Comparatornatural order (compareTo) / external rule (compare)7
    stable sort / TimSortequal elements keep order / Java's object sort7
    FIFO / LIFOqueue order / stack order8
    ArrayDeque / circular arraythe stack+queue class / wrap-around array inside8
    offer/poll/peek vs add/remove/elementreturn null/false vs throw8
    PriorityQueue / binary heap / min-heapsmallest-first queue / array-based tree / parent ≤ children9
    sift up / sift down / heapifyfix after offer / after poll / build from a collection in O(n)9
    top-K patternsize-k min-heap for the k largest9
    unmodifiable view vs immutable copyread-only window vs true snapshot10
    EnumMap / BitSet / WeakHashMapenum keys / compact int set / GC-aware keys10

    Cheat Sheet#

    Declarations you'll type daily

    Java
    List<Integer> list = new ArrayList<>();
    
    Map<String, Integer> cnt = new HashMap<>();
    
    Set<Integer> seen = new HashSet<>();
    
    Map<Integer, List<Integer>> graph = new HashMap<>();
    
    Deque<Integer> stack = new ArrayDeque<>();
    
    Deque<int[]> queue = new ArrayDeque<>();
    
    PriorityQueue<Integer> minH = new PriorityQueue<>();
    
    PriorityQueue<Integer> maxH = new PriorityQueue<>(Comparator.reverseOrder());
    
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    
    TreeMap<Integer, Integer> tm = new TreeMap<>();
    
    Set<List<Integer>> uniqueTriples = new HashSet<>();

    Idioms

    Java
    cnt.merge(k, 1, Integer::sum);                  cnt.getOrDefault(k, 0)
    graph.computeIfAbsent(u, x -> new ArrayList<>()).add(v);
    for (var e : map.entrySet()) { e.getKey(); e.getValue(); }
    if (!seen.add(x)) { /* duplicate */ }
    list.removeIf(x -> x < 0);                      list.sort(Comparator.comparingInt(...).reversed().thenComparing(...));
    Arrays.sort(arr2d, (a, b) -> Integer.compare(a[0], b[0]));     // never a[0] - b[0]
    stack.push(x); stack.pop(); stack.peek();       queue.offer(x); queue.poll(); queue.peek();
    tm.floorKey(k); tm.ceilingKey(k); tm.firstKey(); tm.pollFirstEntry(); tm.headMap(k); tm.tailMap(k);
    top-K largest: min-heap, offer, if (size > k) poll

    Costs

    Output
      ArrayList   get/set O(1) · add end amortized O(1) · add/remove front O(n) · contains O(n)
      HashMap/Set O(1) avg (tree bucket worst O(log n)) · resize at size > 0.75 × capacity, doubles
      TreeMap/Set O(log n) all · floor/ceiling O(log n)
      ArrayDeque  O(1) both ends
      PriorityQ   peek O(1) · offer/poll O(log n) · remove(obj)/contains O(n) · heapify O(n)
      heap index: parent (i−1)/2 · children 2i+1, 2i+2

    Try This Yourself#

    1. Build a tiny HashMap. Write MyHashMap<K, V> with an array of 16 buckets (each a linked list of nodes), put, get, and doubling at 0.75 load. Test it with 1,000 keys against java.util.HashMap. Then make a key class with hashCode() returning 42 always and watch your get slow down.

    2. Build a tiny heap. Write MinHeap on an int[] with offer (sift up) and poll (sift down). Check it against PriorityQueue on random input.

    3. LRU both ways. Implement an LRU cache with LinkedHashMap (Ch 5), then again with a HashMap plus your own doubly linked list — LeetCode 146.

    4. Pick the collection. For each, name the collection and the complexity: (a) the first non-repeating character in a string; (b) all students with scores between 150 and 180; (c) process tasks in the order received; (d) the running median of a stream of numbers (hint: two heaps).