Week 6 Review — Collections
Goal
This review checks whether I can pick a collection by contract and draw a HashMap bucket without hand-waving.
Week 6 topics:
CollectionvsCollectionsvsMapList/ArrayList/LinkedListSetandMapimplementationsHashMaphash, bins, resize, mutable keys- Fail-fast iterators
ComparablevsComparator,TreeSetuniqueness
1. Week 6 big picture
Need order + duplicates? List → ArrayList (default)
Need unique? Set → HashSet
+ insertion order LinkedHashSet
+ sorted TreeSet (compareTo, not equals)
Need lookup by key? Map → HashMap
+ iteration order LinkedHashMap
+ sorted keys TreeMap
+ many threads ConcurrentHashMap (Week 8)
put(k,v): hash → bucket → equals
mutate k after put: lookup misses
for-each + list.remove: ConcurrentModificationException
2. Core memory sentences
Collectionis the interface.Collectionsis the helper.Mapis not aCollection.
Default to
ArrayList; linked lists rarely win in real JVMs.
Setis uniqueness.Mapis lookup.
HashSetis aHashMapwith a dummy value.
Hash picks the bucket;
equalsconfirms the key; collisions list, then tree.
A mutated key stays in the old bucket.
Fail-fast means
modCountchanged; CME is a detector, not a lock.
Remove with
iterator.removeorremoveIf.
Comparableis natural order.Comparatoris an external strategy.
HashSetusesequals.TreeSetusescompareTo.
3. Speak these without notes
- Draw
HashMap.putfromhashCodetoequals. - Why a mutable key disappears.
- Why for-each +
removethrows, and the legal alternative. HashSetvsTreeSetuniqueness.ArrayListvsLinkedListwithout saying “LinkedList is faster for inserts.”
4. Tiny code proofs
Proof A — mutated key
Put a mutable object in a HashMap, change a field used by hashCode, get with the same reference. Confirm a miss. Then iterate entrySet and see the entry still there.
Proof B — CME
For-each an ArrayList and remove inside the loop. Catch ConcurrentModificationException. Repeat with removeIf.
Proof C — TreeSet vs equals
Two objects with equals false and compareTo 0. Add both to HashSet and to TreeSet. Compare sizes.
5. Common mix-ups from this week
| Mix-up | Clear line |
|---|---|
Map is-a Collection | Separate interface; use views |
| LinkedList for inserts | Only if I already have the node |
HashMap always O(1) | Expected, given a good hash |
TreeSet is a sorted HashSet | Comparison defines uniqueness |
| CME means two threads | One thread + for-each remove is enough |
Hashtable for concurrency | ConcurrentHashMap |
6. Interview drill
Open Collections and streams:
ArrayListvsLinkedListvs array- How
HashMapworks internally HashSetvsLinkedHashSetvsTreeSet- Fail-fast vs fail-safe
- Why changing a key after insert breaks a
HashMap equals/hashCodefor aHashSetof entities
And Java fundamentals: Comparable vs Comparator; equals/hashCode.
7. Ready for Week 7?
I am ready if I can draw the bucket picture and remove from a list without CME.
Week 7 is streams: laziness, map/flatMap, and when a loop is clearer.