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) — true if that key has a value, without the risk of get returning null.
  • getOrDefault(key, fallback) — like get, but returns fallback instead of null when the key is missing.
  • remove(key) — deletes a pair by key.
  • size() — how many pairs the map holds.

Common Pitfalls

  • Assuming a HashMap remembers insertion order. Unlike ArrayList, it doesn't guarantee any particular order when you loop through keySet().
  • Calling get() with a key that was never put(). Returns null rather than throwing an error at that point — but if the value type is a primitive wrapper (like the Double offsets above), assigning that null into a double unboxes it and throws NullPointerException right there (Ch.9.2's wrapper-class pitfalls). Use containsKey(key) first, or getOrDefault(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 HashMap when 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 and get() (Ch.9.4).
  • get() on a missing key returns null, which throws NullPointerException the moment it's unboxed into a primitive — check with containsKey()/getOrDefault() instead. remove(key) and size() round out the common operations.

Derived from csawesome-2026: unit-4-data-collections/4.60-optional-hashmap-dictionary-data-structure.md (CSA 4.60)