Skip to content

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

    Java / Collections, From the Inside

    Utilities and Immutable Collections

    List<Integer> l — new ArrayList<>(List.of(3, 1, 2));

    Chapter 10 of 111 min read

    Java
    List<Integer> l = new ArrayList<>(List.of(3, 1, 2));
    
    Collections.reverse(l); // [2, 1, 3]
    
    Collections.swap(l, 0, 2); // [3, 1, 2]
    
    Collections.max(l); // 3   (also min)
    
    Collections.frequency(List.of(1, 2, 1), 1); // 2
    
    Collections.sort(l);
    
    Collections.sort(l, Collections.reverseOrder());
    
    Collections.nCopies(5, 0); // [0, 0, 0, 0, 0] (immutable)
    
    Collections.emptyList();

    Immutable vs unmodifiable view — a subtle interview point:

    Java
    List<Integer> view = Collections.unmodifiableList(l); // a read-only WINDOW onto l
    
    l.add(9);
    
    System.out.println(view); // [3, 1, 2, 9]   ← the view SEES the change
    • Collections.unmodifiableList(l) — you can't modify it through the view, but changes to the original list show through.

    • List.of(...), Map.of(...), Set.of(...), List.copyOf(l) — truly immutable snapshots (and they reject nulls).

    Return immutable copies from methods whose callers shouldn't change your data (encapsulation, Object-Oriented Programming Ch 1).

    Specialised collections worth knowing: EnumMap / EnumSet (keys from an enum, backed by an array/bitmask, very fast — Object-Oriented Programming Ch 11), BitSet (a compact set of small integers, one bit each), WeakHashMap (entries disappear when keys are no longer used elsewhere — used for caches), and the concurrent collections ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue (Concurrency).