Part 04 / Topic 9 of 10
Choosing: array vs. ArrayList vs. HashMap vs. HashSet
One table to decide, not four separate ones:
| You need to... | Reach for | Why |
|---|---|---|
| Store a known, fixed number of same-type values, maybe primitives | array (int[], double[], ...) |
No resizing overhead; can hold primitives directly, no boxing |
| Store a list that grows or shrinks at run time | ArrayList<T> |
add/remove any time; size() always current |
| Look something up by a name/ID, not by position | HashMap<K, V> |
One get(key) call instead of scanning a list for a match |
| Keep a collection with no duplicates, or ask "have I seen this?" fast | HashSet<T> |
add()'s true/false return is the duplicate check |
A worked example: a store's catalog (which items it sells, and at what price) is known and fixed for a given day — a good fit for parallel arrays, or you could argue either way. A shopping cart (how many items Asha scans this visit) is not known ahead of time — a bad fit for an array, a good fit for ArrayList. Turning "item name" into "its price" quickly is a lookup — HashMap. Flagging "you already scanned Milk" is a duplicate check — HashSet. Section 10 builds exactly this combination.
Done here? The practice set for Part 4 — including the solutions — is on the part page.