Unit 08 · lesson

Choose the Structure From the Operations

A common beginner question is:

Which collection is best?

There is no universal best collection. There is a best fit for a particular set of required operations and constraints.

Start with questions.

Must order be preserved?
Can duplicates exist?
Will size change?
Do I need lookup by integer position?
Do I need fast membership checks?
Do I need key -> value association?
Does replacement of an existing key make sense?

The answers narrow the structure.

Case: robot event history

Requirement:

Preserve every event in arrival order, including repeated event types.

A List<Event> is a natural first model. A Set would destroy duplicate events. A Map<String, Event> keyed only by event type could overwrite history.

Case: unique capabilities

Requirement:

Store the unique capability names supported by a device; order is not meaningful.

A Set<String> expresses uniqueness directly.

You could enforce uniqueness manually in a List, but then the algorithm is reimplementing a rule already represented by the structure.

Case: configuration lookup

Requirement:

Given a setting name, retrieve its configured value.

A Map<String, String> exposes the key-value relationship.

Big-O without pretending it is magic

Data-structure performance matters, but do not memorize complexity notation without connecting it to operations.

For this course, the deeper lesson is:

  • an indexed array/list supports direct position-based access;
  • a hash-based set/map is designed for membership/key lookup without scanning every element in the common case;
  • actual performance depends on implementation, data, hashing, memory, and workload.

You do not need a benchmark for every classroom collection choice. You do need to know what operation you are optimizing for.

Refactor repeated variables into a collection

Start with:

String error1 = "E14";
String error2 = "E07";
String error3 = "E14";
String error4 = "E22";

Create three possible models:

  • List<String> preserving every event;
  • Set<String> preserving only unique codes;
  • Map<String, Integer> mapping each code to a count.

Each answers a different question.

For the map version, produce:

E14 -> 2
E07 -> 1
E22 -> 1

Design decision record

For a dataset of your choice, write a short ADR-style note:

Decision:
Required operations:
Alternatives considered:
Why chosen:
Tradeoff accepted:
Evidence case:

Then implement enough Java to demonstrate the operation that justified your choice.

What counts as evidence

"I used HashMap because maps are good" is not enough.

"The requirement retrieves a status by unique device ID; a Map makes ID the explicit key, while a List would require a search over records" is a design argument.

That is the habit we are building before object-oriented design adds more choices.