SyntaxPilot
Courses/Java/Lesson 29

Java · Lesson 29 of 51 · 12 min

Generics

queued

These are the notes for Java episode 29. A list of names for the class photo crashes at runtime because someone slipped a number in, and two obvious fixes (one class per type, or one box of Object) both fail. Today's fix: generics, a way to leave a blank for a type in a class or method, fill it in when you use it, and let the compiler check every use. We'll also cover generic methods, bounded types (<T extends Number>), wildcards (?) and type erasure. Every example was run with javac 21.

The problem: a list that crashes at runtime

The class teacher keeps a list of names for the photo caption. Anyone can write on it, and someone writes 78 by mistake. The mistake is found only on printing day.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList names = new ArrayList();
        names.add("Asha");
        names.add("Ravi");
        names.add(78);              // oops: a number
        for (int i = 0; i < names.size(); i++) {
            String n = (String) names.get(i);
            System.out.println(n.toUpperCase());
        }
    }
}

The compiler only prints a note:

Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Then, at runtime:

ASHA
RAVI
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
    at Main.main(Main.java:10)

An ArrayList with no angle brackets is a raw type: it stores everything as Object (the parent of every class, episode 22), so add accepts anything and the compiler can't check what's inside.

Obvious fix 1: one class per type

class IntBox {
    private int item;
    void set(int item) { this.item = item; }
    int get() { return item; }
}

class StringBox {
    private String item;
    void set(String item) { this.item = item; }
    String get() { return item; }
}

public class Main {
    public static void main(String[] args) {
        IntBox a = new IntBox();       a.set(78);
        StringBox b = new StringBox(); b.set("Asha");
        System.out.println(a.get() + " " + b.get());
    }
}
78 Asha

Safe, but the two classes are the same code with one word changed. A hundred types means a hundred copies.

Obvious fix 2: one box of Object

class Box {
    private Object item;
    void set(Object item) { this.item = item; }
    Object get() { return item; }
}

public class Main {
    public static void main(String[] args) {
        Box box = new Box();
        box.set(78);
        String s = (String) box.get();
        System.out.println(s);
    }
}
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
    at Main.main(Main.java:11)

One class, but the box forgets what went in: every get needs a cast, and every cast can crash at runtime. We want both: one class, and compile-time checks.

The fix: a type parameter

At a railway cloakroom In Java
One cloakroom design, the same racks for everything class Box<T>: one class, written once
A token labelled "suitcase", chosen at the counter Box<String>: T becomes String
The clerk refuses a bicycle on a suitcase token name.set(78) doesn't compile
You get a suitcase back, no guessing String s = name.get(), no cast
  • A type parameter (T) is a blank that means "some type, chosen later". You write it in angle brackets after the class name and use it wherever the type goes.
  • A class with a type parameter is a generic class.
  • Box<String> fills the blank: for this box, T is String everywhere. String here is the type argument.
  • new Box<>(): the empty <> is the diamond operator: "same type as the left side, work it out".
  • Naming convention: T type, E element, K key, V value, N number.
class Box<T> {
    private T item;
    void set(T item) { this.item = item; }
    T get() { return item; }
}

public class Main {
    public static void main(String[] args) {
        Box<String> name = new Box<>();
        name.set("Asha");
        String s = name.get();          // no cast
        Box<Integer> marks = new Box<>();
        marks.set(78);
        int m = marks.get();
        System.out.println(s + " scored " + m);
    }
}
Asha scored 78

The runtime crash becomes a compile error

Box<String> name = new Box<>();
name.set(78);
Main.java:10: error: incompatible types: int cannot be converted to String
        name.set(78);
                 ^

That's the whole point of generics: mistakes are caught when you write the code, not when a user runs it.

ArrayList is generic too

ArrayList is declared as class ArrayList<E>. Always give the type:

ArrayList<String> names = new ArrayList<>();
names.add("Asha");
names.add("Ravi");
names.add(78);
Main.java:8: error: incompatible types: int cannot be converted to String
        names.add(78);
                  ^

Rule: never use raw types.

Two type parameters: Pair

class Pair<K, V> {
    private final K key;
    private final V value;
    Pair(K key, V value) { this.key = key; this.value = value; }
    K getKey() { return key; }
    V getValue() { return value; }
}

public class Main {
    public static void main(String[] args) {
        Pair<String, Integer> p = new Pair<>("Asha", 78);
        Pair<Integer, Boolean> q = new Pair<>(204, true);
        System.out.println(p.getKey() + " -> " + p.getValue());
        System.out.println("Room " + q.getKey() + " booked: " + q.getValue());
    }
}
Asha -> 78
Room 204 booked: true

HashMap<K, V> (episode 32) stores exactly these key-value pairs.

Generic methods

When only one method needs the blank, declare it before the return type:

public class Main {
    static <T> T last(T[] items) {
        return items[items.length - 1];
    }

    public static void main(String[] args) {
        String[] names = { "Asha", "Ravi", "Meena" };
        Integer[] marks = { 78, 91, 64 };
        String n = last(names);
        int m = last(marks);
        System.out.println(n + " " + m);
    }
}
Meena 64

Java infers T from the argument (String for names, Integer for marks), so you never write it.

Bounded types:

An average for any list of numbers. First try:

static <T> double average(List<T> items) {
    double sum = 0;
    for (T x : items) sum += x.doubleValue();
    return sum / items.size();
}
Main.java:6: error: cannot find symbol
        for (T x : items) sum += x.doubleValue();
                                  ^
  symbol:   method doubleValue()
  location: variable x of type T
  where T is a type-variable:
    T extends Object declared in method <T>average(List<T>)

An unbounded T could be anything (a String, a Student), so only Object's methods are allowed. Put a bound (a limit) on it:

import java.util.List;

public class Main {
    static <T extends Number> double average(List<T> items) {
        double sum = 0;
        for (T x : items) sum += x.doubleValue();
        return sum / items.size();
    }

    public static void main(String[] args) {
        System.out.println(average(List.of(78, 91, 64)));
        System.out.println(average(List.of(9.5, 8.0)));
    }
}
77.66666666666667
8.75

Number is the parent class of Integer, Double, Long, ... and has doubleValue(). Passing a List<String> now fails to compile:

error: method average in class Main cannot be applied to given types;
  required: List<T>
  found:    List<String>
  reason: inference variable E has incompatible bounds
    upper bounds: Number,Object
    lower bounds: String

In generics, extends is used for both classes and interfaces: <T extends Comparable<T>> means "T can be compared" (episode 34).

Wildcards: ?

static void printAll(List<Object> items) { ... }
List<String> names = List.of("Asha", "Ravi");
printAll(names);
Main.java:11: error: incompatible types: List<String> cannot be converted to List<Object>
        printAll(names);
                 ^

A String is an Object, but a List<String> is not a List<Object>: a List<Object> promises you can add anything, and that would let printAll add 78 into your list of names. (Generics are invariant.)

The wildcard ? means "some type I don't know":

import java.util.List;

public class Main {
    static void printAll(List<?> items) {
        for (Object x : items) System.out.print(x + " ");
        System.out.println();
    }

    static double total(List<? extends Number> items) {
        double sum = 0;
        for (Number x : items) sum += x.doubleValue();
        return sum;
    }

    public static void main(String[] args) {
        printAll(List.of("Asha", "Ravi"));
        printAll(List.of(78, 91));
        System.out.println(total(List.of(78, 91)) + " " + total(List.of(2.5, 0.5)));
    }
}
Asha Ravi 
78 91 
169.0 3.0
Wildcard Means You can
List<?> a list of some unknown type read items as Object; not add (except null)
List<? extends Number> a list of Number or a subclass read items as Number; not add
List<? super Integer> a list of Integer or a parent (Number, Object) add Integers; read as Object

Rule of thumb, PECS: Producer Extends, Consumer Super. If the method only reads from the list, use extends; if it only adds, use super.

Type erasure

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> a = new ArrayList<>();
        ArrayList<Integer> b = new ArrayList<>();
        System.out.println(a.getClass() == b.getClass());
        System.out.println(a.getClass().getName());
    }
}
true
java.util.ArrayList

The compiler uses the type arguments to check your code and insert the casts, then erases them: at runtime Box<T> is just a Box of Object (or of the bound, e.g. Number). Generics were added in Java 5 this way so old code kept working. Consequences:

You can't Real message Instead
Box<int> error: unexpected type / required: reference / found: int Box<Integer> (episode 28)
new T() error: unexpected type / required: class / found: type parameter T pass a factory or a Class<T>
x instanceof List<String> the type isn't there at runtime x instanceof List<?>

Common mistakes (and the real error messages)

Mistake Real message Why Fix
ArrayList names = new ArrayList(); ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (at runtime) raw type: no checks ArrayList<String>
Box<String> b; b.set(78); error: incompatible types: int cannot be converted to String that's generics working put a String in, or use Box<Integer>
<T> then x.doubleValue() error: cannot find symbol / symbol: method doubleValue() T could be any type <T extends Number>
printAll(List<Object>) with a List<String> error: incompatible types: List<String> cannot be converted to List<Object> generics are invariant List<?>
Box<int> error: unexpected type / required: reference / found: int T is erased to Object Box<Integer>
new T() error: unexpected type / required: class / found: type parameter T T unknown at runtime pass a factory

Mini project: a generic shelf

A Shelf that holds any comparable type and finds its largest item, a swappable Pair, and a wildcard counter.

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

class Shelf<T extends Comparable<T>> {
    private final List<T> items = new ArrayList<>();
    void add(T item) { items.add(item); }
    T max() {
        T best = items.get(0);
        for (T x : items) if (x.compareTo(best) > 0) best = x;
        return best;
    }
    int size() { return items.size(); }
}

class Pair<A, B> {
    final A first; final B second;
    Pair(A first, B second) { this.first = first; this.second = second; }
    Pair<B, A> swap() { return new Pair<>(second, first); }
    public String toString() { return "(" + first + ", " + second + ")"; }
}

public class Main {
    static int count(List<?> list, Object x) {
        int c = 0;
        for (Object o : list) if (o.equals(x)) c++;
        return c;
    }

    public static void main(String[] args) {
        Shelf<Integer> marks = new Shelf<>();
        marks.add(78); marks.add(91); marks.add(64);
        Shelf<String> names = new Shelf<>();
        names.add("Asha"); names.add("Ravi"); names.add("Meena");
        System.out.println("Top mark: " + marks.max() + ", last name A-Z: " + names.max());
        Pair<String, Integer> p = new Pair<>("Asha", 78);
        System.out.println(p + " -> " + p.swap());
        System.out.println("78 appears " + count(List.of(78, 91, 78), 78) + " times");
    }
}
Top mark: 91, last name A-Z: Ravi
(Asha, 78) -> (78, Asha)
78 appears 2 times

Practice

  1. Write Pair<A, B> with a swap() that returns Pair<B, A>.
  2. Write a generic max(T[] a) with <T extends Comparable<T>>.
  3. Write count(List<?> list, Object x): how many times x appears.
  4. Predict the error: Box<String> b = new Box<>(); b.set(3.5);
Solutions

1 and 3 are in the mini project above.

2.

static <T extends Comparable<T>> T max(T[] a) {
    T best = a[0];
    for (T x : a) if (x.compareTo(best) > 0) best = x;
    return best;
}
// max(new Integer[] { 3, 9, 4 }) → 9,  max(new String[] { "kiwi", "apple", "mango" }) → mango

4. error: incompatible types: double cannot be converted to String.

Quick quiz

List<Integer> a = new ArrayList<>();
List<String> b = new ArrayList<>();
a.add(5);
b.add("5");

System.out.println(a.get(0).equals(5) + " "
    + (a.getClass() == b.getClass()) + " " + b.get(0).length());

A) true false 1 B) true true 1 C) false true 5 D) It doesn't compile

Answer

B. a.get(0) is the Integer 5, so equals(5) is true. Both lists are java.util.ArrayList at runtime (type erasure): true. "5".length() is 1.

true true 1

Interview questions

  1. What are generics and why use them? Type parameters on classes and methods; they give compile-time type safety, remove casts, and let one class work with many types.
  2. What is a raw type? A generic class used without type arguments (ArrayList); it holds Object and loses all checks. Kept only for old code.
  3. What is type erasure? The compiler checks types and inserts casts, then removes type arguments, so ArrayList<String> and ArrayList<Integer> are the same class at runtime.
  4. Why can't you use primitives as type arguments? After erasure T becomes Object, and primitives aren't objects. Use wrappers.
  5. Is List<String> a subtype of List<Object>? No, generics are invariant. Use List<?> or List<? extends Object>.
  6. What is a bounded type parameter? A limit on T, like <T extends Number>, which lets you call the bound's methods.
  7. Explain ? extends vs ? super (PECS). ? extends T for reading (a producer), ? super T for writing (a consumer).
  8. Why can't you write new T()? The actual type isn't known at runtime because of erasure.
  9. What is the diamond operator? <> on the right side; the compiler infers the type arguments (Java 7+).

Glossary

Term Meaning Example
Generics Classes and methods with type parameters, checked by the compiler ArrayList<String>
Type parameter A placeholder for a type, written in <> T in class Box<T>
Type argument The real type that fills the blank String in Box<String>
Generic class A class with one or more type parameters class Pair<K, V>
Generic method A method with its own type parameter static <T> T last(T[] a)
Raw type A generic class used without <> ArrayList names
Cast Telling the compiler to treat a value as another type (String) box.get()
ClassCastException A runtime crash when a cast is wrong Integer cast to String
Diamond operator <> that lets the compiler infer the type new Box<>()
Type inference The compiler working out a type for you last(names) → T = String
Bounded type A type parameter with a limit <T extends Number>
Number The parent class of the numeric wrappers Integer, Double
Wildcard ?, an unknown type in a parameter List<?>
Upper-bounded wildcard Some subtype of a type List<? extends Number>
Lower-bounded wildcard Some parent of a type List<? super Integer>
Invariance List<String> is not a List<Object> the printAll error
PECS Producer Extends, Consumer Super read → extends, add → super
Type erasure Type arguments removed after compiling ArrayList<String>.class == ArrayList.class
Compile time vs runtime When javac checks the code vs when the program runs generics move errors to compile time

Summary

  • A raw list holds Object, so a wrong item crashes only at runtime.
  • One class per type is copy-paste; one Object box needs casts and still crashes.
  • Generics: class Box<T> leaves a blank for the type; Box<String> fills it, and the compiler checks every use, with no casts.
  • Generic methods (<T> T last(T[] a)) infer T from the arguments.
  • Bounds (<T extends Number>) let you call the bound's methods; wildcards (List<?>, ? extends, ? super) accept families of lists.
  • Type erasure: types are checked, then removed, so no Box<int>, no new T().
  • Next: Java's real collections: ArrayList, LinkedList and the Iterator (episode 30).