Skip to content

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

    Java / Collections, From the Inside

    HashSet, LinkedHashMap and an LRU Cache

    HashSet<E> is a set of unique items. Inside, it's literally a HashMap<E, Object> where each item is a key and every value is the same

    Chapter 5 of 114 min read

    The Plain Picture#

    • A guest list: you only care whether someone is on it, not any extra information about them.

    • A visitors' book: entries stay in the order people signed.

    • A small desk that holds only 2 files — when a third arrives, the file you haven't touched for longest goes back to the cabinet.

    The Real Names#

    • HashSet<E> is a set of unique items. Inside, it's literally a HashMap<E, Object> where each item is a key and every value is the same dummy object. Same costs: add, contains, remove are O(1) average. add returns false if the item was already there — which is how the duplicate checker in Big-O and Complexity worked.

    • LinkedHashMap / LinkedHashSet add a doubly linked list through all the entries, so iteration follows insertion order. Slightly more memory; same O(1) operations.

    • A LinkedHashMap built with accessOrder = true moves an entry to the end every time it's read — giving least-recently-used first order. Overriding removeEldestEntry makes it evict automatically: an LRU cache (least recently used) in 5 lines.

    Under the Hood#

    Iteration order — the three maps side by side (same four keys inserted in the same order):

    Output
    HashMap [priya, vikram, rahul, aisha] | LinkedHashMap [rahul, priya, aisha, vikram] | TreeMap [aisha, priya, rahul, vikram]
                     ↑ bucket order                     ↑ insertion order                          ↑ sorted order (Ch 6)

    Never rely on HashMap iteration order. It can change between Java versions and after a resize. If order matters, choose LinkedHashMap (insertion) or TreeMap (sorted).

    An LRU cache:

    Java
    class LruCache<K, V> extends LinkedHashMap<K, V> {
        private final int capacity;
    
        LruCache(int capacity) {
            super(16, 0.75f, true); // true = ACCESS order, not insertion order
            this.capacity = capacity;
        }
    
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > capacity; // evict the least recently used when over capacity
        }
    }
    
    LruCache<String, String> cache = new LruCache<>(2);
    
    cache.put("q1", "Cells");
    
    cache.put("q2", "DNA");
    
    cache.get("q1"); // touching q1 makes it "recently used"
    
    cache.put("q3", "Atoms"); // over capacity → evict the eldest: q2
    
    System.out.println("LRU keys: " + cache.keySet()); // LRU keys: [q1, q3]

    "Design an LRU cache" is a famous interview problem (LeetCode 146, Design Problems (coming soon)). In the interview you usually must build it yourself from a HashMap plus your own doubly linked list — which is exactly what LinkedHashMap does inside. Caching in real systems: Caching (coming soon).

    Check yourself

    4 questions
    1

    How is HashSet implemented?

    Show answer

    As a HashMap whose keys are the set's elements and whose values are a shared dummy object.

    2

    What does set.add(x) return if x is already present?

    Show answer

    false.

    3

    HashMap vs LinkedHashMap vs TreeMap — what iteration order does each give?

    Show answer

    No guaranteed order (bucket order) / insertion order (or access order) / sorted key order.

    4

    How does LinkedHashMap become an LRU cache?

    Show answer

    Construct it with accessOrder = true so reads move entries to the end, and override removeEldestEntry to return true when size exceeds the capacity.