Skip to content

Module 9 · Collections and Generics — topic 4 of 5

Generics

Type parameters for classes, interfaces and methods, type safety without casts, bounded types, wildcards (? extends, ? super), the PECS rule, and type erasure.

Beginner 18 min read·Lesson 33 of 39 in Java Programming

Learning objectives

  • Write generic classes and generic methods
  • Use bounded type parameters and wildcards
  • Explain type erasure and its limitations

Definition

Generics let classes, interfaces and methods be parameterised by types, so the same code works with many types while the compiler checks type safety. A type parameter such as <T> is replaced by a concrete type argument when the generic is used.

Introduction

Before Java 5, collections held plain Objects: you had to cast everything you took out and hope it was the right type. Generics move those checks to compile time. List<String> can only contain strings, and get returns a String — no casts and no ClassCastException surprises.

Why it matters

Every collection and much of the standard library is generic; reading their signatures requires understanding generics.

Writing your own generic utilities (a Pair, a cache, a repository) lets you reuse code safely.

Detailed explanation

Generic classes. class Box<T> { private T value; T get() { ... } }. T is a type parameter; Box<String> and Box<Integer> are parameterised types. By convention: T (type), E (element), K and V (key and value), R (result).

Generic methods declare their own type parameters before the return type: static <T> T firstOrDefault(List<T> list, T fallback). The compiler usually infers T from the arguments.

Bounded types. <T extends Comparable<T>> accepts only types that can be compared, so the method may call compareTo. <T extends Number> allows doubleValue().

Invariance. A List<Integer> is *not* a List<Number>, even though Integer is a Number — otherwise you could add a Double to a list of Integers.

Wildcards. List<? extends Number> means 'a list of some subtype of Number': you can read Numbers from it but not add (except null). List<? super Integer> means 'a list of Integer or a supertype': you can add Integers but reading gives only Object. The rule of thumb PECS: *Producer Extends, Consumer Super*. List<?> is a list of unknown type.

Type erasure. Generic type information is checked at compile time and then erased: at run time a List<String> is just a List. Consequently you can't write new T(), new T[n], instanceof List<String>, or use primitives as type arguments (use Integer).

Syntax

Java
class Pair<A, B> {
private final A first; private final B second;
Pair(A first, B second) { this.first = first; this.second = second; }
A first() { return first; }
B second() { return second; }
}
static <T extends Comparable<T>> T max(List<T> items) { ... }
static double sum(List<? extends Number> nums) { ... } // producer: extends
static void fill(List<? super Integer> out) { out.add(1); } // consumer: super
  • Use the diamond: new Pair<>("a", 1).
  • Primitive types can't be type arguments; use wrappers.
  • Generic code compiles with no casts at the call site.

Code examples

A generic class and method

Java
import java.util.List;
public class Main {
public static void main(String[] args) {
Box<String> name = new Box<>("Asha");
Box<Integer> age = new Box<>(21);
String n = name.get(); // no cast needed
int a = age.get() + 1;
System.out.println(n + " will be " + a);
System.out.println(firstOr(List.of("x", "y"), "none") + " " + firstOr(List.<Integer>of(), -1));
Pair<String, Double> p = new Pair<>("pi", 3.14159);
System.out.println(p + " swapped " + p.swap());
}
static <T> T firstOr(List<T> list, T fallback) {
return list.isEmpty() ? fallback : list.get(0);
}
}
class Box<T> {
private final T value;
Box(T value) { this.value = value; }
T get() { return value; }
}
record Pair<A, B>(A first, B second) {
Pair<B, A> swap() { return new Pair<>(second, first); }
}
Output
Asha will be 22
x -1
Pair[first=pi, second=3.14159] swapped Pair[first=3.14159, second=pi]

Bounded type parameters

Java
import java.util.List;
public class Main {
static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T item : items) if (item.compareTo(best) > 0) best = item;
return best;
}
static <T extends Number> double average(List<T> nums) {
double sum = 0;
for (T n : nums) sum += n.doubleValue();
return nums.isEmpty() ? 0 : sum / nums.size();
}
public static void main(String[] args) {
System.out.println(max(List.of(3, 17, 9)) + " " + max(List.of("pear", "apple", "zucchini")));
System.out.println(average(List.of(1, 2, 3, 4)) + " " + average(List.of(2.5, 3.5)));
}
}
Output
17 zucchini
2.5 3.0

More examples

Wildcards, PECS and a generic repository

Java
import java.util.*;
import java.util.function.Predicate;
public class Main {
static double sum(Collection<? extends Number> source) { // producer: extends
double total = 0;
for (Number n : source) total += n.doubleValue();
return total;
}
static void addSquares(Collection<? super Integer> sink, int n) { // consumer: super
for (int i = 1; i <= n; i++) sink.add(i * i);
}
static <T> void copy(List<? extends T> src, List<? super T> dst) { dst.addAll(src); }
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3);
List<Double> doubles = List.of(0.5, 1.5);
System.out.println(sum(ints) + " " + sum(doubles));
List<Number> numbers = new ArrayList<>();
List<Object> objects = new ArrayList<>();
addSquares(numbers, 3);
addSquares(objects, 2);
copy(ints, numbers);
System.out.println(numbers + " " + objects);
Repository<String, Book> repo = new Repository<>(Book::isbn);
repo.save(new Book("978-1", "Effective Java", 2018));
repo.save(new Book("978-2", "Head First Java", 2022));
repo.save(new Book("978-3", "Java Concurrency in Practice", 2006));
System.out.println(repo.find("978-2").map(Book::title).orElse("?") + ", missing: " + repo.find("000").isPresent());
System.out.println(repo.findAll(b -> b.year() >= 2018));
List<String> erased = new ArrayList<>();
System.out.println("same runtime class: " + (erased.getClass() == new ArrayList<Integer>().getClass()));
}
}
record Book(String isbn, String title, int year) { }
class Repository<K, V> {
private final Map<K, V> items = new LinkedHashMap<>();
private final java.util.function.Function<V, K> keyOf;
Repository(java.util.function.Function<V, K> keyOf) { this.keyOf = keyOf; }
void save(V item) { items.put(keyOf.apply(item), item); }
Optional<V> find(K key) { return Optional.ofNullable(items.get(key)); }
List<V> findAll(Predicate<? super V> test) {
List<V> out = new ArrayList<>();
for (V v : items.values()) if (test.test(v)) out.add(v);
return out;
}
}
Output
6.0 2.0
[1, 4, 9, 1, 2, 3] [1, 4]
Head First Java, missing: false
[Book[isbn=978-1, title=Effective Java, year=2018], Book[isbn=978-2, title=Head First Java, year=2022]]
same runtime class: true

Step-by-step explanation

  • sum(Collection<? extends Number>) accepts a List<Integer> or a List<Double> because it only *reads* Numbers — a producer, so extends.
  • addSquares(Collection<? super Integer>) accepts a List<Number> or List<Object> because it only *writes* Integers — a consumer, so super.
  • copy combines both: read Ts from a producer, write them to a consumer.
  • Repository<K, V> works for any value type; it is told how to extract the key with a function (Book::isbn) and returns Optional<V> instead of null.
  • Because of type erasure, ArrayList<String> and ArrayList<Integer> share one runtime class.

Expected output

Running “Wildcards, PECS and a generic repository” prints exactly:

TextOutput
6.0 2.0
[1, 4, 9, 1, 2, 3] [1, 4]
Head First Java, missing: false
[Book[isbn=978-1, title=Effective Java, year=2018], Book[isbn=978-2, title=Head First Java, year=2022]]
same runtime class: true

Practical applications

  • Collections, Optional, Stream and Comparator are all generic
  • Generic DAOs and repositories in Spring Data
  • Utility methods such as Collections.max and Collections.sort
  • Typed result wrappers such as Result<T> or Page<T>

Best practices

  • Never use raw types in new code.
  • Follow PECS when choosing wildcards for parameters.
  • Prefer generic methods and bounded types over casting.

Common mistakes

Using raw types

Avoid

List names = new ArrayList();
names.add(42);
String s = (String) names.get(0); // ClassCastException

Prefer

List<String> names = new ArrayList<>();
names.add("Asha");

Raw types turn off generic checking; mistakes are only discovered at run time.

Expecting List<Integer> to be a List<Number>

Avoid

static double total(List<Number> xs) { ... }
total(List.of(1, 2)); // compile error

Prefer

static double total(List<? extends Number> xs) { ... }

Generic types are invariant; use a wildcard to accept lists of any Number subtype.

Important notes

  • Type erasure is why Java can't create generic arrays (new T[10]); use a List<T> or pass a Class<T>.
  • Generic methods can have explicit type arguments when inference fails: List.<Integer>of().

Key takeaways

  • Generics add compile-time type safety and remove casts.
  • Bounds (extends) restrict type parameters; wildcards make parameters flexible.
  • PECS: producers use extends, consumers use super; types are erased at run time.

Try it yourself

  1. 1
    Write a generic Stack<T> class backed by an ArrayList with push, pop and peek.
  2. 2
    Write static <K, V extends Comparable<V>> K keyOfMax(Map<K, V> map).

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhy can't you write `List<int>`?
  • ModerateWhy doesn't `List<Number> nums = new ArrayList<Integer>();` compile?
  • ModerateFollowing PECS, which parameter type suits a method that only ADDS Integers to a list?
Practise this topic