Skip to content

Checkpoint: Typed Shelf

The Course
•
20 min study

Combine generic types with ownership. A reusable container should preserve element types without exposing its private mutable list. Do not use Object, raw collections or unchecked casts. Remember that generic typing cannot decide whether null should be accepted.

Work through the example

Type-safe access and state isolation are separate guarantees. Here the generic helper returns a new List<T>, retaining the element type and separating membership. Clearing it has no effect on the source. Because the elements are strings, no mutable element state can leak through the shared references.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("Read");
        List<String> snapshot = snapshot(source);
        snapshot.clear();
        System.out.println(source.get(0).length());
        System.out.println(snapshot.size());
    }

    static <T> List<T> snapshot(List<T> values) {
        return new ArrayList<>(values);
    }
}
Check your prediction
Text
4
0

Compare the behavior

Validation still happens before mutation. This small list helper rejects a null value and leaves the old contents unchanged. An expected exception check must fail explicitly if no exception occurs, otherwise removing validation could make the test pass unnoticed.

Trace the changed case Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> values = new ArrayList<>();
        try {
            add(values, null);
            throw new AssertionError("null accepted");
        } catch (IllegalArgumentException expected) {
            System.out.println(values.size());
        }
    }

    static <T> void add(List<T> values, T value) {
        if (value == null) {
            throw new IllegalArgumentException("value required");
        }
        values.add(value);
    }
}
Check your prediction
Text
0

Plan your acceptance cases

Predict each row before you write the class.

CaseExpected behaviorSkill it checks
String and Integer shelvesTyped access without castsGeneric class
Clear a returned snapshotStored values remainOwnership
Reject null after one valid entrySize remains oneValidation before mutation
Shelf<Number> gets addAll of a List<Integer>Accepted; size 2? extends T wildcard
addAll of a list containing a nullRejected; size unchanged, none of that list addedValidate the whole batch first

When your version works, change addAll's parameter to List<T>. Which line stops compiling? Put the wildcard back.

Practice independently

Exercise

Checkpoint: Typed Shelf: practice

Build Shelf<T> with add(T), addAll, size() and snapshot(). Reject null, keep insertion order and return a copied mutable list. addAll must accept a list of T or of any subtype of T, so that a Shelf<Number> can take a List<Integer>, and it adds nothing at all if any element is null. Check every row of the table above and print Shelf checks passed.

Your workspace Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        System.out.println("Build and check Shelf<T>");
    }
}
Hint 1: the idea

Reuse List<T> for storage, but keep it private. Each accessor must respect the ownership contract.

Hint 2: a first step

Write the class declaration and field first. Implement size by delegating to the list; implement snapshot by copying it. For addAll, ask two questions before writing it: which lists should it accept (try passing a list of a subtype), and what must happen to the shelf if one element is null?

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        Shelf<String> titles = new Shelf<>();
        titles.add("Read");
        List<String> copy = titles.snapshot();
        copy.clear();
        check(titles.size() == 1);
        check(titles.snapshot().get(0).equals("Read"));
        Shelf<Integer> minutes = new Shelf<>();
        minutes.add(25);
        check(minutes.snapshot().get(0) == 25);
        try {
            titles.add(null);
            throw new AssertionError("null accepted");
        } catch (IllegalArgumentException expected) {
            check(titles.size() == 1);
        }

        Shelf<Number> numbers = new Shelf<>();
        List<Integer> whole = List.of(1, 2);
        numbers.addAll(whole);
        check(numbers.size() == 2);
        List<Integer> withNull = new ArrayList<>();
        withNull.add(3);
        withNull.add(null);
        try {
            numbers.addAll(withNull);
            throw new AssertionError("null in batch accepted");
        } catch (IllegalArgumentException expected) {
            check(numbers.size() == 2);
        }
        System.out.println("Shelf checks passed");
    }

    static void check(boolean condition) {
        if (!condition) {
            throw new AssertionError("shelf contract");
        }
    }
}

final class Shelf<T> {
    private final List<T> values = new ArrayList<>();

    void add(T value) {
        if (value == null) {
            throw new IllegalArgumentException("value required");
        }
        values.add(value);
    }

    void addAll(List<? extends T> items) {
        for (T item : items) {
            if (item == null) {
                throw new IllegalArgumentException("value required");
            }
        }
        values.addAll(items);
    }

    int size() {
        return values.size();
    }

    List<T> snapshot() {
        return new ArrayList<>(values);
    }
}

Expected output:

Text
Shelf checks passed

List<? extends T> is the Day 4 decision: addAll only reads from items, so it can accept a list of any subtype, and a List<Integer> reaches a Shelf<Number>. With List<T> that call does not compile, because a List<Integer> is not a List<Number>. The first loop checks every element before the second step changes anything, so a batch with a null leaves the shelf at 2 instead of 3. snapshot copies, so clearing the copy cannot touch the shelf.

Change it and test again

Return the field directly from snapshot, then run the checks. Restore it and remove null validation: a different check should fail. Add a duplicate value and decide whether the shelf should keep it; a shelf is a sequence here, not a set.

Explain before moving on

Name the guarantee provided by T, the guarantee provided by validation, and the guarantee provided by copying. Which one would you need to revisit if T were a mutable object?

Was this article helpful?

Your response is saved on this device.