Skip to content
Generics
step 1/5

Reading — step 1 of 5

Learn

~1 min readGenerics and Collections

Generics let you write code that works with different types without losing type safety. Replaces the old Object + cast pattern.

List<String> names = new ArrayList<>();
names.add("Ada");
String first = names.get(0);   // no cast, no ClassCastException

Generic class:

class Box<T> {
    private T value;
    public Box(T value) { this.value = value; }
    public T get() { return value; }
}

Box<Integer> intBox = new Box<>(42);
Box<String> strBox = new Box<>("hi");

Generic method:

public static <T> T firstOf(List<T> list) {
    return list.get(0);
}

Bounded type parameters — restrict T:

public static <T extends Comparable<T>> T max(List<T> list) {
    T m = list.get(0);
    for (T x : list) if (x.compareTo(m) > 0) m = x;
    return m;
}

Wildcards:

  • List<?> — unknown type (read-only essentially)
  • List<? extends Number> — Number or any subclass (covariant read)
  • List<? super Integer> — Integer or any supertype (contravariant write)

Mnemonic: PECS — Producer Extends, Consumer Super.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…