GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java15 / 25

Generics and Collections

List, Set, and Map with type contracts

14.1 Learning Objectives

By the end of this chapter, you should be able to:

  • choose between List, Set, and Map;
  • explain how generics prevent unsafe casts;
  • create a simple generic class;
  • register commands by name;
  • distinguish between mutable and immutable collections.

14.2 Choosing a Collection

The needs of the problem guide the choice of collection.

Figure 14.1. The needs of the problem guide the choice of collection.

StructureUse when
List<E>order and duplicates matter
Set<E>elements must not repeat
Map<K, V>a value is looked up by a key

The interface describes the contract; the implementation determines performance and ordering details. For example, HashSet typically offers fast lookup, but the Set interface alone does not guarantee a specific implementation.

14.3 Registering Commands with Map

import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

interface Command {
    String name();
    String execute();
}

final class CommandRegistry {
    private final Map<String, Command> commands = new LinkedHashMap<>();

    void register(Command command) {
        String key = command.name().toLowerCase(Locale.ROOT);
        if (commands.putIfAbsent(key, command) != null) {
            throw new IllegalArgumentException("Duplicate command: " + key);
        }
    }

    String execute(String input) {
        String key = input.strip().toLowerCase(Locale.ROOT);
        Command command = commands.get(key);
        return command == null
                ? "Unknown command."
                : command.execute();
    }
}

The map replaces linear search: the normalized name serves as the key and the polymorphic object serves as the value. There is no need to introduce Runnable; the Command contract expresses the domain much better.

14.4 Generic Class

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

final class Repository<T> {
    private final List<T> items = new ArrayList<>();

    void add(T item) {
        items.add(item);
    }

    List<T> list() {
        return List.copyOf(items);
    }
}

T represents a type chosen by whoever uses the class. Repository<String> accepts strings; Repository<Command> accepts commands. The compiler prevents invalid mixing of types.

14.5 Complete Example

import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

public class Chapter14Generics {
    interface Command {
        String execute();
    }

    private final Map<String, Command> commands = new LinkedHashMap<>();

    void register(String name, Command command) {
        String key = name.toLowerCase(Locale.ROOT);
        if (commands.putIfAbsent(key, command) != null) {
            throw new IllegalArgumentException("Duplicate command.");
        }
    }

    String process(String input) {
        Command command =
                commands.get(input.strip().toLowerCase(Locale.ROOT));
        return command == null ? "Unknown command." : command.execute();
    }

    public static void main(String[] args) {
        Chapter14Generics registry = new Chapter14Generics();
        registry.register("help", () -> "Available commands.");
        registry.register("tip", () -> "Use Map to look up by key.");

        System.out.println(registry.process("TIP"));
    }
}

The lambda expression implements the single operation of Command. It appears here only after the contract itself has been studied; a named class remains appropriate whenever behavior requires state or extra clarity.

List.of and Map.of create collections that do not accept modifications. Use them for fixed data. For registries that grow during execution, choose a mutable implementation such as ArrayList or LinkedHashMap.

The complete example is in examples/src/Chapter14Generics.java.

14.6 Verifiable Practice

  1. Reject empty command names.
  2. Prevent duplicate command registration.
  3. Create a Set<String> holding tip categories.
  4. Use Repository<String> to store quiz questions.

Test cases:

  • registering the same key twice throws an exception;
  • " TIP " finds the tip command;
  • an unknown command returns the default message;
  • the list returned by the repository cannot alter its internal state.