Unit 08 · lesson

Set and Map Encode Different Questions

A collection choice should make an important rule easier to express.

Set: is this value a member?

Imagine tracking unique team numbers encountered in a log.

var teams = new HashSet<Integer>();
teams.add(2180);
teams.add(341);
teams.add(2180);

IO.println(teams.size());

Adding 2180 twice does not create a duplicate membership entry.

The core question for a Set is often:

Have we seen this value?
Is this value a member?
How many unique values exist?

Do not rely on a HashSet's iteration order as a meaningful sorted or insertion order.

Map: what value belongs to this key?

A Map models key-value relationships.

var scores = new HashMap<Integer, Integer>();
scores.put(2180, 95);
scores.put(341, 88);

IO.println(scores.get(2180));

The team number is a key. The score is the associated value.

A second put with the same key replaces the prior mapping:

scores.put(2180, 101);

That may be correct or may destroy needed history. The data model decides.

If you need every score event over time, one key-to-one-value map is probably not enough.

Presence is not the same as a stored null

Maps can make absence reasoning more subtle. Use methods like containsKey when you need to distinguish whether a mapping exists.

For this course, keep values non-null unless the requirement explicitly needs null semantics. It makes the early model easier to verify.

Translate requirements

Choose a structure for each:

  1. Preserve the order of every lap time, including duplicates.
  2. Record whether each unique student ID has checked in.
  3. Map a command name to a help message.
  4. Track every unique error code seen in a run.
  5. Preserve every message in arrival order.

For each, name:

  • what must be stored;
  • whether duplicates matter;
  • whether order matters;
  • whether lookup is by position, membership, or key;
  • your proposed structure.

Build a small command dictionary

var help = new HashMap<String, String>();
help.put("start", "begin the run");
help.put("stop", "end the run");
help.put("status", "show current state");

Test existing and absent commands.

Do not simply print null for an unknown command and call it finished. Create a visible missing-command rule.

Evidence

Take one dataset and model it two ways, such as a List and a Set or a List and a Map. Show one operation where the difference becomes observable.

The comparison should prove why the structure matters. If both versions are indistinguishable for every operation you test, your test did not exercise the design choice.