Choosing and using lists, sets, maps and deques.
Key points, notes and past questions
Collections Framework
The largest share of a paper.
- Which container?
- Pick the interface by the question: position, uniqueness, lookup or ends.
- The loop variable must accept the element type;
intacceptsIntegerby unboxing. - Walk a map through
keySet(),values()orentrySet(). - Collections hold references, so one list can be reached through several names.
- Assigning to the loop variable does not change the collection.
- Three map orders
HashMap: order unspecified.LinkedHashMap: first insertion.TreeMap: sorted keys.- Putting an existing key replaces the value and keeps one entry; a linked map keeps the key's place.
- Natural string order puts digits, then capitals, then small letters.
- A
TreeMapcopy sorts whatever the source hands over, and later changes to the copy leave the source alone.
- Totals: getOrDefault and merge
getOrDefaultreads only; the default covers an absent key.- Total pattern:
m.put(k, m.getOrDefault(k, 0) + x). mergestores directly for a new key; otherwisefunction(old, new).- A
nullfunction result removes the key.
- Sets, sameness and order
- Sets refuse repeats;
addreturnsfalsefor one. - Hash order is unspecified; linked keeps first arrival; tree sorts.
- Override
equalsandhashCodetogether. - A tree set judges sameness by order and needs comparable elements.
- Grouping into tree sets gives sorted groups whatever the arrival order.
- Sets refuse repeats;
- Removing while walking
it.remove()takes no argument and deletes the lastnext()result.- One
removepernext; earlier or twice throwsIllegalStateException. - Changing the list directly during a walk usually throws on a later
next(). - A for-each loop hides an iterator, so the same rule applies.
- List iterators: edit while walking
- The cursor is a gap;
nextandpreviouscross one element. removeandsetuse the last returned element;adduses the gap.- After
add, cross another element beforesetorremove. ListIteratorexists for lists only.
- The cursor is a gap;
- Stacks, queues and deques
- Stack: newest out. Queue: oldest out.
push,pop,poll,peekuse the head;add,offeruse the tail.- A
Stackprints bottom first; a deque prints head first. pollandpeekgivenullon empty;popandremovethrow.
- Loops that look or remove
peekandelementkeep the head;poll,remove,popdelete it.- A loop that tests only the size ends only if each turn shrinks the deque.
- From both ends with an odd count, use
> 1to leave the middle alone. - Compare boxed values with
equals;==on them compares references.
Notes32 past questions in this topic
Week 5: Generic programming, subtyping, runtime behaviourWeek 7: Exceptions, assertions, packages, loggingAll Java topics and weeks