← SEARCHABLE ARCHIVE
Java · 2026-07-30

Java from Basics to Mastery — Part 5

Choosing Generics and Collections to Fit Your Purpose

INTERACTIVE READING MODE →

The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.

Java collections store a variety of data, but each data structure does different things. If you use generics together, you can check for type errors when compiling without having to convert the retrieved value every time.

List, Set, Map

List<String> party = new ArrayList<>();
Set<Integer> unlockedIds = new HashSet<>();
Map<Integer, Item> itemById = new HashMap<>();

party.add("Rose");
unlockedIds.add(10);
itemById.put(10, new Item(10, "Potion"));

List allows order and duplication, and Set deals with the presence or absence of non-duplicate values. Map finds values ​​through keys.

The order of HashMap is not guaranteed. If sorting or input order is a contract, you should choose an implementation that suits that purpose.

Search safely

Item item = itemById.get(10);
if (item != null) {
    System.out.println(item.getName());
}

get returns null if the key does not exist. Avoiding designs that store null itself as a value prevents confusion between None and the null value.

generic class

public final class Registry<T extends Identifiable> {
    private final Map<Integer, T> values = new HashMap<>();

    public void add(T value) {
        values.put(value.getId(), value);
    }

    public Optional<T> find(int id) {
        return Optional.ofNullable(values.get(id));
    }
}

T extends Identifiable is a restriction that the type to be stored must provide an ID. Registry<Item> and Registry<Monster> reuse the same rules, but the values ​​are not mixed.

Rely on interfaces rather than implementations

If you set the field and parameter types to a List or Map interface, only the necessary operations remain in the contract. However, if performance characteristics are important, you should also know whether the actual implementation is ArrayList or LinkedList.

Collection selection is not just a matter of data quantity. The purpose of use, such as order, duplication, search key, and frequency of change, must first be determined.