dev only

Optional: 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:

for (String name : subsystemStatus.keySet())
{
    String status = subsystemStatus.get(name);
    System.out.println(name + ": " + status);
}

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 — check for that if 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 get().

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