Chapters & contents Lesson 20 of 20
3 min read
Java foundationsExpanded reading

Choose collections by the contract your data needs

Compare ordered entries, uniqueness, and key-based lookup before choosing an implementation.

What you’ll learn

  • Distinguish List, Set, and Map semantics
  • Trace duplicate handling and replacement
  • Explain why mutable keys can break a map’s assumptions

Start with the question the data must answer

A course application has several collections with different meanings. The visible lesson sequence needs an order and may use position-based access. Completed lesson identifiers need uniqueness. A lookup from lesson identifier to title needs one associated title per key. These requirements suggest List, Set, and Map respectively. Choosing HashMap or ArrayList before stating the contract reverses the reasoning. Interfaces describe useful promises; implementations add performance characteristics and other constraints that you must inspect for the actual workload.

Trace duplicates without guessing

Put lesson-A, lesson-B, and lesson-A into an ordinary list: all three entries can remain in their inserted order. Add those identifiers to a set and there are two distinct elements under its equality rules. Put key lesson-A with title Intro into a map, then put the same key with title Introduction: the second put replaces the associated value. A map does not hold two separate mappings for the same key. If your domain allows several revisions per lesson, model the revision in the key or store an explicit collection of revisions.

java · Worked example
import java.util.HashMap;
import java.util.Map;

class Titles {
    public static void main(String[] args) {
        Map<String, String> titles = new HashMap<>();
        titles.put("lesson-A", "Intro");
        titles.put("lesson-A", "Introduction");
        System.out.println(titles.size());  // 1
        System.out.println(titles.get("lesson-A"));  // Introduction
    }
}

Equality is part of the design

Hash-based collections depend on compatible equals and hashCode behavior. Imagine a mutable key whose equality depends on a title field. Insert the key while its title is Intro, then change the field to Basics. The key is still an object, but the collection’s lookup assumptions may no longer hold because the value affecting equality changed while it was stored. Prefer stable identifiers as keys, and define equality deliberately for domain types. A field used only for display often makes a poor identity.

Do not infer order or immutability from appearance

A HashMap does not promise the presentation order a learner expects. If the interface needs lesson order, store or derive that order using a structure with an appropriate guarantee. Likewise, an unmodifiable collection prevents supported structural changes through that collection, but does not automatically make mutable element objects immutable. A copied outer collection can still refer to shared elements. Separate the ownership and mutability of the container from those of the objects it contains when designing an API boundary.

Choose a small behavior test

Write tests for the domain promise rather than for a coincidental internal layout. Verify that completing a lesson twice does not increase a distinct-completion count, that a course sequence preserves the published order, and that renaming a title does not lose lookup by stable lesson identifier. Then measure if performance becomes a real concern. Different implementations can have different costs for lookup, insertion, and iteration. A well-chosen contract gives you room to change implementation while preserving what callers can rely on.

Try it yourself

You need an ordered syllabus, a unique set of completed lesson IDs, and a title lookup by stable lesson ID. Choose an interface for each. Explain why a mutable title object should not be used as the lookup key.

Show a possible solution

Use List for the ordered syllabus, Set for unique completed IDs, and Map for ID-to-title lookup. A key whose equals or hashCode inputs change while stored can invalidate a hash-based map’s lookup assumptions; use a stable identifier key instead.

Check your understanding

Try 14 questions across java foundations. Read each explanation and revisit anything that needs another pass.

Practise this subject

Go to the source

Use these primary references to check details and explore the topic further.

Saved in this browser. Signed-in progress syncs to your account.