HashMap (Dictionary) Data Structure
Key-Value Pairs
A HashMap stores pairs — each unique key maps to a value, like a real dictionary mapping a word to its definition:
import java.util.HashMap;
HashMap<Integer, Double> motorOffsets = new HashMap<Integer, Double>();
motorOffsets.put(5, 0.02); // CAN ID 5's calibration offset is 0.02
motorOffsets.put(6, -0.01);
double offset = motorOffsets.get(5); // 0.02
put(key, value) adds or replaces a pair; get(key) retrieves the value for a key.
When to Reach for a HashMap
Arrays and ArrayList are naturally indexed by position (0, 1, 2...). A HashMap is for when the natural "index" is something else entirely — a name, an ID number, a label — and you want to look values up by that instead of a position:
HashMap<String, String> subsystemStatus = new HashMap<String, String>();
subsystemStatus.put("Intake", "Ready");
subsystemStatus.put("Shooter", "Spinning Up");
Looping Through Every Pair
keySet() gives you every key, which you can then use with get() to reach each value. This loops with the for-each form (for (type item : collection)) — Lesson 9.4 covers it in full, but the short version: it visits every key in turn, with no index needed:
for (String name : subsystemStatus.keySet())
{
String status = subsystemStatus.get(name);
System.out.println(name + ": " + status);
}
Other Useful Methods
containsKey(key)—trueif that key has a value, without the risk ofgetreturningnull.getOrDefault(key, fallback)— likeget, but returnsfallbackinstead ofnullwhen the key is missing.remove(key)— deletes a pair by key.size()— how many pairs the map holds.
Common Pitfalls
- Assuming a
HashMapremembers insertion order. UnlikeArrayList, it doesn't guarantee any particular order when you loop throughkeySet(). - Calling
get()with a key that was neverput(). Returnsnullrather than throwing an error at that point — but if the value type is a primitive wrapper (like theDoubleoffsets above), assigning thatnullinto adoubleunboxes it and throwsNullPointerExceptionright there (Ch.9.2's wrapper-class pitfalls). UsecontainsKey(key)first, orgetOrDefault(key, fallback), whenever a lookup might legitimately miss.
Key Takeaways
- A
HashMap<KeyType, ValueType>stores unique keys mapped to values. put(key, value)adds or replaces a pair;get(key)retrieves the value.- Reach for a
HashMapwhen you naturally look things up by name/ID rather than by position. keySet()gives every key, for looping through all pairs with a for-each loop andget()(Ch.9.4).get()on a missing key returnsnull, which throwsNullPointerExceptionthe moment it's unboxed into a primitive — check withcontainsKey()/getOrDefault()instead.remove(key)andsize()round out the common operations.
Derived from csawesome-2026: unit-4-data-collections/4.60-optional-hashmap-dictionary-data-structure.md (CSA 4.60)