synopsis · Java for DSA · chapter 5
Java Toolkit & Collections
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
The Collections Framework = interfaces (
List,Deque,Set,Map) + ready-made data structures behind them. Pick by the operation you need most. - use it when
Stack/queue →
ArrayDeque. Seen it? Count? →HashSet/HashMap. Sorted or nearest key →TreeMap. Next smallest →PriorityQueue. Indexed list →ArrayList. - cost
HashMap O(1) avg · TreeMap O(log n) · PriorityQueue offer/poll O(log n), peek O(1) · ArrayList get O(1), add amortized O(1), remove(0) O(n).
- cost
ArrayList grows by 1.5× (
old + (old >> 1)): 10 lakh adds = only 30 grows (the first 10 slots, then 29 × 1.5), ~2.4 copies per add. Rare O(n) copies → amortized O(1). - template
map.merge(w, 1, Integer::sum);counts.map.computeIfAbsent(k, x -> new ArrayList<>()).add(v);groups. - template
Max-heap:
new PriorityQueue<>(Collections.reverseOrder()). Pairs:new PriorityQueue<int[]>((a, b) -> Integer.compare(a[0], b[0])). - trap
Integer==compares references: true for −128..127 (the cache), false for 128 on a default JVM. Useequals, or unbox toint. - trap
int c = map.get(k)on a missing key → NullPointerException.(a, b) -> a - boverflows. UsegetOrDefaultandInteger.compare. - pro tip
Declare by interface:
Deque<Integer> st = new ArrayDeque<>();. Then say why out loud: "ArrayDeque, O(1) at both ends."
Shaky on a card? Open the chapter or flip its recall cards.