Java NotesRohit’s interview study guide
Chapter 04

Generics

Generic classes and methods compared with TypeScript generics, type erasure and what it forbids, bounded types and the ? extends / ? super wildcards (PECS), and the traps: no primitives, raw types, heap pollution and covariant arrays. Every example was run with Java 25 (Eclipse Temurin 25.0.5.1).

Try it yourself. As in chapter 01: for each example, make an empty folder, save every code box in it under the name in its caption, and type the $ lines of the Terminal box there. Compiler errors and exceptions on this page are shown on purpose; the text says so. The TypeScript comparisons in the text were checked with TypeScript 6.0 (tsc --strict).

5 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Generic classes and methods

Added

A type parameter lets one class or method work with many types while the compiler still checks every use. List<String> is a list that the compiler guarantees holds only strings; Map<String, Integer> maps strings to integers. You used these in Java 5 and 6, and TypeScript generics look almost the same: class Page<T>, function first<T>(items: T[]): T.

What's worth knowing now is how to write generic code, not just use it:

  • A generic class or record declares its type parameters after its name: record Page<T>(List<T> items, int number, int totalPages). Inside, T stands for whatever type the user picks.
  • A generic method declares its own type parameters before the return type: static <T> T firstOrElse(List<T> items, T fallback). The compiler infers T from the arguments at each call, as TypeScript does.
  • The diamond new ArrayList<>() (Java 7) lets the compiler fill in the type arguments on the right from the left: no more new HashMap<String, List<Integer>>() written twice.
  • Type arguments must be reference types: List<Integer>, never List<int> (see Generics gotchas).

The mental model: a type parameter is a blank on a form that the caller fills in, and once it's filled in (Page<Product>), the compiler checks every line against it. Before Java 5, collections held Object and you cast on every read; generics moved that cast from your code, where it could be wrong, into the compiler, which checks it.

Pages.java
record Page<T>(List<T> items, int number, int totalPages) {
    boolean isLast() {
        return number == totalPages;
    }

    <R> Page<R> map(Function<T, R> mapper) {
        var mapped = new ArrayList<R>();
        for (T item : items) {
            mapped.add(mapper.apply(item));
        }
        return new Page<>(mapped, number, totalPages);
    }
}

static <T> T firstOrElse(List<T> items, T fallback) {
    return items.isEmpty() ? fallback : items.get(0);
}

void main() {
    Page<String> names = new Page<>(List.of("desk", "chair", "lamp"), 2, 2);
    Page<Integer> lengths = names.map(String::length);
    IO.println(names + " last: " + names.isLast());
    IO.println(lengths);

    String first = firstOrElse(names.items(), "none");
    int firstLength = firstOrElse(lengths.items(), 0);
    IO.println(first + " " + firstLength + " " + firstOrElse(List.of(), "empty"));
}
Terminal
$ java Pages.java
Page[items=[desk, chair, lamp], number=2, totalPages=2] last: true
Page[items=[4, 5, 4], number=2, totalPages=2]
desk 4 empty
What’s happening
  1. record Page<T> declares one type parameter. new Page<>(List.of("desk", "chair", "lamp"), 2, 2) uses the diamond: the compiler sees the variable is a Page<String> and fills in T = String.
  2. map is a generic method inside a generic class: it has its own parameter R, the type of the result. names.map(String::length) passes a function from String to Integer, so the compiler infers R = Integer and returns a Page<Integer>.
  3. The first line prints the record with its items: Page[items=[desk, chair, lamp], number=2, totalPages=2] last: true. The second prints the mapped page, [4, 5, 4], with the same page numbers.
  4. firstOrElse is a static generic method. For names.items() the compiler infers T = String, so the result can go straight into a String with no cast. For lengths.items() it infers Integer, which unboxes into int.
  5. firstOrElse(List.of(), "empty") works too: List.of() has no elements to infer from, so the compiler uses the other argument and picks T = String, returning the fallback, empty.
  6. In TypeScript this whole file would read almost the same. The difference you'll feel is in what the compiler refuses, next.
AdvancedThe checks you get, and the casts you no longer write

The point of generics is that mistakes fail at compile time instead of at the line that reads the value. Here is the same bug written with a raw List, the way Java 1.4 code worked, and with a List<String>:

Raw.java
public class Raw {
    public static void main(String[] args) {
        java.util.List names = new java.util.ArrayList();
        names.add("Rohit");
        names.add(42);
        for (Object o : names) {
            String name = (String) o;
            System.out.println(name.toUpperCase());
        }
    }
}
Typed.java
import java.util.ArrayList;
import java.util.List;

public class Typed {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Rohit");
        names.add(42);
        for (String name : names) {
            System.out.println(name.toUpperCase());
        }
    }
}
Terminal
$ java Raw.java
Raw.java:4: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
        names.add("Rohit");
                 ^
  where E is a type-variable:
    E extends Object declared in interface List
Raw.java:5: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
        names.add(42);
                 ^
  where E is a type-variable:
    E extends Object declared in interface List
2 warnings
ROHIT
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 Raw.main(Raw.java:7)
$ java Typed.java
Typed.java:8: error: no suitable method found for add(int)
        names.add(42);
             ^
    method List.add(String) is not applicable
      (argument mismatch; int cannot be converted to String)
    method List.add(int,String) is not applicable
      (actual and formal argument lists differ in length)
1 error
error: compilation failed
What’s happening
  1. The raw List accepts anything, so names.add(42) compiles. The compiler notices the raw type and prints an "unchecked" warning for each add, but warnings don't stop it: the program runs.
  2. At run time the loop prints ROHIT, then reaches the Integer, and the cast (String) o fails with ClassCastException. The bug was the add, but the crash is at the read, which in real code may be in another class or another day.
  3. With List<String>, names.add(42) is a compile error: no add(int) fits a list of strings, so nothing runs. The bug is caught on the line that causes it.
  4. The typed loop needs no cast: for (String name : names) is checked by the compiler. The cast still exists in the bytecode (see Type erasure), but the compiler has proved it can't fail.
AdvancedExplicit type arguments

Inference usually works, but sometimes there's nothing to infer from, and you can pass the type argument yourself with a type witness: Collections.<String>emptyList(). You'll mostly see it in older code and in chained calls.

Witness.java
import java.util.Collections;
import java.util.List;

public class Witness {
    static <T> List<T> twice(T value) {
        return List.of(value, value);
    }

    public static void main(String[] args) {
        List<String> empty = Collections.emptyList();
        var alsoEmpty = Collections.<String>emptyList();
        var numbers = Witness.<Number>twice(7);
        System.out.println(empty + " " + alsoEmpty + " " + numbers);
        numbers = List.of(1.5, 2);
        System.out.println(numbers);
    }
}
Terminal
$ java Witness.java
[] [] [7, 7]
[1.5, 2]
What’s happening
  1. List<String> empty = Collections.emptyList(); infers T = String from the variable's type: the target type.
  2. With var there's no target type, so Collections.<String>emptyList() states it. Without the witness, var alsoEmpty would be a List<Object>.
  3. Witness.<Number>twice(7) forces T = Number, so numbers is a List<Number> rather than the List<Integer> that inference would pick. It prints [] [] [7, 7].
  4. Because it's a List<Number>, the variable can later hold List.of(1.5, 2), a list mixing a Double and an Integer: [1.5, 2]. A List<Integer> variable couldn't.

#Type erasure

Added

Java added generics in Java 5 without changing the JVM or breaking existing class files, and the way it did that is type erasure: the compiler checks your generic types, then erases the type arguments from the compiled code. List<String> and List<Integer> both become plain List in the bytecode; T becomes its bound (Object unless you said otherwise); and the compiler inserts a cast wherever you read a T back out.

TypeScript erases too, but more. In TypeScript, all types disappear and nothing is checked at run time. In Java, objects still know their class (getClass(), instanceof String and casts all work at run time, chapter 02); only the type arguments are gone. So at run time a List<String> knows it's an ArrayList, but not that it holds strings.

The mental model: generics are a compile-time contract, and the bytecode keeps only the signature on the outside of the envelope. The JVM sees ArrayList and Object; the compiler made sure, before it threw the details away, that only strings went in.

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

public class Erase {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        List<Integer> numbers = new ArrayList<>();
        System.out.println(names.getClass() == numbers.getClass());
        System.out.println(names.getClass().getName());

        names.add("Rohit");
        String first = names.get(0);
        System.out.println(first);
    }
}
Terminal
$ javac Erase.java
$ java Erase
true
java.util.ArrayList
Rohit
$ javap -c Erase | grep -E 'List\.(add|get):|checkcast'
        60: invokeinterface #41,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
        68: invokeinterface #45,  2           // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
        73: checkcast     #49                 // class java/lang/String
What’s happening
  1. names.getClass() == numbers.getClass() is true: at run time both are just java.util.ArrayList. There is no ArrayList<String> class.
  2. javap -c shows the bytecode. List.add takes (Ljava/lang/Object;)Z, an Object (and returns a boolean): the compiler checked that you passed a String, then compiled an ordinary add(Object) call.
  3. List.get returns Ljava/lang/Object;. The next instruction is a checkcast to java/lang/String: the cast you didn't write. This is where a polluted list would finally fail (Generics gotchas).
  4. The program prints true, java.util.ArrayList and Rohit. The generic types did all their work in javac; the JVM ran code that is the same as Java 1.4 code with casts.
AdvancedWhat erasure forbids

Because T doesn't exist at run time, anything that needs to know T while the program runs can't be written:

Forbidden.java
import java.util.List;

public class Forbidden<T> {
    T make() {
        return new T();
    }

    boolean isListOfStrings(Object o) {
        return o instanceof List<String>;
    }

    T[] array() {
        return new T[10];
    }

    static T shared;
}
Clash.java
import java.util.List;

public class Clash {
    void save(List<String> names) {}

    void save(List<Integer> ids) {}
}
Terminal
$ javac Forbidden.java
Forbidden.java:16: error: non-static type variable T cannot be referenced from a static context
    static T shared;
           ^
Forbidden.java:5: error: unexpected type
        return new T();
                   ^
  required: class
  found:    type parameter T
  where T is a type-variable:
    T extends Object declared in class Forbidden
Forbidden.java:9: error: Object cannot be safely cast to List<String>
        return o instanceof List<String>;
               ^
Forbidden.java:13: error: generic array creation
        return new T[10];
               ^
4 errors
$ javac Clash.java
Clash.java:6: error: name clash: save(List<Integer>) and save(List<String>) have the same erasure
    void save(List<Integer> ids) {}
         ^
1 error
What’s happening
  1. new T(): at run time there's no T to construct, and the compiler can't even know T has a no-argument constructor. The error says it needs a class and found a type parameter.
  2. o instanceof List<String>: the JVM could check List, but not <String>. Since Java 16, instanceof accepts a generic type only when the compiler can prove the check is safe; from Object it can't, so it reports that Object cannot be safely cast to List<String>. (o instanceof List<?> is allowed: "some kind of list".)
  3. new T[10]: an array must know its element class at run time (see covariant arrays below), so "generic array creation" is refused.
  4. static T shared: a static field belongs to the class, and there's one class for every Forbidden<String>, Forbidden<Integer> and so on, so a static field can't have the type T.
  5. In Clash.java, both save methods erase to save(List), the same signature in the class file, so the compiler reports a name clash: they "have the same erasure". Overloads must differ after erasure; give them different names (saveNames, saveIds).
AdvancedWorking around erasure: pass the Class

When code really needs the type at run time (to create instances, to deserialise JSON), the convention is to pass a Class<T> object, a type token. And because generic types in declarations (fields, method signatures, superclasses) are kept in the class file for reflection, libraries can recover a full generic type from a subclass: that's how Jackson's TypeReference and Spring's ParameterizedTypeReference work.

Tokens.java
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Tokens {
    static <T> T create(Class<T> type) throws ReflectiveOperationException {
        return type.getDeclaredConstructor().newInstance();
    }

    static <T> List<T> onlyOfType(List<?> items, Class<T> type) {
        var result = new ArrayList<T>();
        for (Object item : items) {
            if (type.isInstance(item)) {
                result.add(type.cast(item));
            }
        }
        return result;
    }

    abstract static class TypeRef<T> {
        java.lang.reflect.Type type() {
            return ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        StringBuilder sb = create(StringBuilder.class);
        System.out.println("created: " + sb.append("ok"));

        List<Object> mixed = List.of("a", 1, "b", 2.5);
        List<String> strings = onlyOfType(mixed, String.class);
        System.out.println("strings: " + strings);

        var ref = new TypeRef<Map<String, List<Integer>>>() {};
        System.out.println("captured: " + ref.type());
    }
}
Terminal
$ java Tokens.java
created: ok
strings: [a, b]
captured: java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
What’s happening
  1. create(StringBuilder.class) receives the class object, so it can do at run time what new T() can't: find the no-argument constructor and call it. T is inferred from the argument as StringBuilder, so no cast is needed: created: ok.
  2. onlyOfType uses the token to filter: type.isInstance(item) is a run-time instanceof, and type.cast(item) a checked cast. From ["a", 1, "b", 2.5] it keeps [a, b], typed as List<String>.
  3. new TypeRef<Map<String, List<Integer>>>() {} creates an anonymous subclass, and a subclass's declaration (extends TypeRef<Map<String, List<Integer>>>) is stored in its class file with the full generic type.
  4. getGenericSuperclass() reads that declaration back, and ref.type() prints java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>. Erasure removed type arguments from objects, not from declarations.
  5. You'll meet this pattern whenever a library must know a generic type at run time, for example new TypeReference<List<Product>>() {} when Jackson reads a JSON array.

#Bounded types and wildcards

Added

Two separate tools, both about saying "not any type, but a type that…":

A bounded type parameter restricts what T can be, so the method can call methods of the bound. <T extends Comparable<T>> T max(List<T> items) means "any T that can compare itself with another T", which lets the body call item.compareTo(best). TypeScript writes the same thing as <T extends Comparable<T>>. (extends is used for interfaces too in a bound.)

Wildcards are about variance, and they exist because Java generics are invariant: a List<Integer> is not a List<Number>, even though an Integer is a Number. That sounds pedantic until you see why: if a List<Integer> could be passed as a List<Number>, the method could add(2.5) to it, and your list of integers would contain a Double. So Java makes you say at each use what you need:

  • List<? extends Number>: "a list of some subtype of Number". You can read Numbers out of it, but can't add (it might be a List<Double>). It's a producer.
  • List<? super Integer>: "a list of Integer or some supertype of it". You can add Integers, but reading gives only Object. It's a consumer.

The rule of thumb is PECS: Producer Extends, Consumer Super. The JDK's Collections.copy is the textbook case: its signature is <T> void copy(List<? super T> dest, List<? extends T> src), reading from src and writing into dest.

TypeScript does it differently: its arrays are covariant, so const mixed: (number | string)[] = nums; compiles and mixed.push("oops") then puts a string into your number[] with no error. Java's design refuses that at compile time.

The mental model: ? extends is a vending machine (things come out); ? super is a post box (things go in).

Bounds.java
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 double total(List<? extends Number> numbers) {
    double sum = 0;
    for (Number n : numbers) {
        sum += n.doubleValue();
    }
    return sum;
}

static void addCounts(List<? super Integer> target, int upTo) {
    for (int i = 1; i <= upTo; i++) {
        target.add(i);
    }
}

void main() {
    IO.println(max(List.of(3, 9, 4)) + " " + max(List.of("pear", "apple", "plum")));

    List<Integer> ints = List.of(1, 2, 3);
    List<Double> doubles = List.of(0.5, 0.25);
    IO.println(total(ints) + " " + total(doubles));

    List<Number> numbers = new ArrayList<>();
    List<Object> objects = new ArrayList<>();
    addCounts(numbers, 3);
    addCounts(objects, 2);
    objects.add("not a number");
    IO.println(numbers + " " + objects);

    List<Number> copyInto = new ArrayList<>(List.of(0, 0, 0, 0));
    Collections.copy(copyInto, ints);
    IO.println(copyInto);
}
Terminal
$ java Bounds.java
9 plum
6.0 0.75
[1, 2, 3] [1, 2, not a number]
[1, 2, 3, 0]
What’s happening
  1. max has a bounded type parameter, T extends Comparable<T>, so inside the loop the compiler allows item.compareTo(best). Integer and String both implement Comparable of themselves, so max works for both: 9 and plum (strings compare alphabetically).
  2. total(List<? extends Number>) accepts a List<Integer> and a List<Double>. Every element is read as a Number and converted with doubleValue(): 6.0 and 0.75. With a plain List<Number> parameter, both calls would fail to compile.
  3. addCounts(List<? super Integer>) accepts any list that can hold Integers: a List<Number> gets [1, 2, 3] and a List<Object> gets [1, 2]. It couldn't accept a List<Double>.
  4. The List<Object> can hold anything, so "not a number" is added after: [1, 2, not a number]. That's fine, and it's also why reading from a List<? super Integer> only gives you Object.
  5. Collections.copy(dest, src) is PECS in the JDK: dest is List<? super T> and src is List<? extends T>, so with T = Integer it copies a List<Integer> into a List<Number>, overwriting the first three elements: [1, 2, 3, 0]. (It copies into existing positions: dest must already be at least as long as src.)
Is a List of Integer a List of Number?
Invariant.java
static double sum(List<Number> numbers) {
    double total = 0;
    for (Number n : numbers) {
        total += n.doubleValue();
    }
    return total;
}

void main() {
    List<Integer> ints = List.of(1, 2, 3);
    IO.println(sum(ints));
}
Show answer
Terminal
$ java Invariant.java
Invariant.java:11: error: method sum in class Invariant cannot be applied to given types;
    IO.println(sum(ints));
               ^
  required: List<Number>
  found:    List<Integer>
  reason: argument mismatch; List<Integer> cannot be converted to List<Number>
1 error
error: compilation failed
What’s happening
  1. It doesn't print anything: it doesn't compile. sum asks for a List<Number> and ints is a List<Integer>.
  2. Generics are invariant: List<Integer> and List<Number> are unrelated types, whatever the relationship between Integer and Number. The compiler reports that a List<Integer> cannot be converted to List<Number>.
  3. The reason: sum could call numbers.add(2.5), which is legal for a List<Number>, and that would put a Double into your list of integers.
  4. The fix is sum(List<? extends Number> numbers): now the method promises only to read, and any list of a Number subtype is accepted.
AdvancedWhy you can't add to a List of ? extends
NoAdd.java
static void addOne(List<? extends Number> numbers) {
    numbers.add(1);
}

static Object firstOf(List<? super Integer> numbers) {
    Integer first = numbers.get(0);
    return first;
}

void main() {
    addOne(new ArrayList<Double>());
}
Terminal
$ java NoAdd.java
NoAdd.java:2: error: no suitable method found for add(int)
    numbers.add(1);
           ^
    method List.add(CAP#1) is not applicable
      (argument mismatch; int cannot be converted to CAP#1)
    method List.add(int,CAP#1) is not applicable
      (actual and formal argument lists differ in length)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Number from capture of ? extends Number
NoAdd.java:6: error: incompatible types: CAP#1 cannot be converted to Integer
    Integer first = numbers.get(0);
                               ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object super: Integer from capture of ? super Integer
2 errors
error: compilation failed
What’s happening
  1. In addOne, the list could be a List<Double> (as main passes), a List<Integer> or a List<Long>, and the compiler doesn't know which. No value except null is safe to add to all of them, so numbers.add(1) is refused.
  2. The message talks about CAP#1: the compiler's name for "the specific unknown type behind this ?", a capture of the wildcard. "int cannot be converted to CAP#1" is wildcard-speak for "you can't put things into a producer".
  3. In firstOf, the list could be a List<Integer>, List<Number> or List<Object>, so get(0) is only known to return an Object, not an Integer; that's refused too. You can't take things out of a consumer, except as Object.
  4. Both errors are reported and nothing runs. When a method both reads and writes Ts, use a plain List<T>; wildcards are for parameters that only produce or only consume.
AdvancedThe bound you'll see in the JDK

Collections.max is declared as <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll). Read it with PECS: the collection is a producer of Ts (? extends T), and Comparable<? super T> lets T be compared by a comparison defined on a supertype. That matters for a class hierarchy where only the parent implements Comparable:

Versions.java
import java.util.Collections;
import java.util.List;

public class Versions {
    static <T extends Comparable<T>> T strictMax(List<T> items) {
        return Collections.max(items);
    }

    public static void main(String[] args) {
        List<Release> releases = List.of(new Release(17), new Release(25), new Release(21));
        System.out.println("Collections.max: " + Collections.max(releases));
        System.out.println("strictMax: " + strictMax(releases));
    }
}

class Version implements Comparable<Version> {
    final int number;

    Version(int number) {
        this.number = number;
    }

    @Override
    public int compareTo(Version other) {
        return Integer.compare(number, other.number);
    }

    @Override
    public String toString() {
        return "Java " + number;
    }
}

class Release extends Version {
    Release(int number) {
        super(number);
    }
}
Terminal
$ java Versions.java
Versions.java:12: error: method strictMax in class Versions cannot be applied to given types;
        System.out.println("strictMax: " + strictMax(releases));
                                           ^
  required: List<T>
  found:    List<Release>
  reason: inference variable T has incompatible equality constraints Version,Release
  where T is a type-variable:
    T extends Comparable<T> declared in method <T>strictMax(List<T>)
1 error
error: compilation failed
What’s happening
  1. Release extends Version, and only Version implements Comparable<Version>. So a Release is a Comparable<Version>, not a Comparable<Release>.
  2. Collections.max(releases) is happy: with T = Release, its bound Comparable<? super Release> accepts Comparable<Version>, because Version is a supertype of Release.
  3. strictMax uses the simpler bound T extends Comparable<T>, which would need Release to implement Comparable<Release>. It doesn't, so the call strictMax(releases) fails to compile: the list says T is Release, the bound says T is Version, and the compiler reports exactly that clash ("incompatible equality constraints Version,Release"). Nothing runs, so the Collections.max line never prints either.
  4. That's why library signatures look so dense: Comparable<? super T> is the general form, and T extends Comparable<T> the version that's easier to read but works for fewer types. In your own code, the simple form is usually fine; write the general one in reusable utilities.

#Generics gotchas

Added

Most generics trouble comes from three design decisions: erasure (above), only reference types as type arguments, and backward compatibility with pre-generics code, which is why raw types still compile. Add one more contrast that interviewers love: arrays are covariant and checked at run time; generics are invariant and checked at compile time.

  • No primitives. List<int> doesn't compile; you write List<Integer> and every element is a boxed object (chapter 02). For large amounts of numbers, an int[] or an IntStream avoids the boxing. Project Valhalla is the long-term work in this area (its value classes are first targeted as a preview in JDK 28); none of it is in Java 25.
  • Raw types (List with no type argument) switch the checks off for that variable. They exist so Java 1.4 code still compiles; in new code they're a mistake, and the compiler warns with "unchecked" warnings.
  • Heap pollution: when a raw type or an unchecked cast puts the wrong type into a generic collection, nothing fails until a later line reads it back through the compiler's hidden cast.
  • Arrays vs generics: String[] is an Object[] (covariant), so a wrong store compiles and fails at run time with ArrayStoreException. List<String> is not a List<Object>, so the same mistake doesn't compile.

The mental model: an unchecked warning is the compiler saying "I can no longer guarantee the casts I'm inserting". Treat it like an error unless you can prove it safe.

Covariance.java
public class Covariance {
    public static void main(String[] args) {
        String[] names = {"ana", "maya"};
        Object[] objects = names;
        System.out.println("an Object[] view of a String[]: " + objects.length + " elements");
        try {
            objects[0] = 42;
        } catch (ArrayStoreException e) {
            System.out.println("ArrayStoreException: " + e.getMessage());
        }
        System.out.println("names[0] is still " + names[0]);
    }
}
Invariance.java
import java.util.ArrayList;
import java.util.List;

public class Invariance {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("ana", "maya"));
        List<Object> objects = names;
        objects.add(42);
    }
}
Terminal
$ java Covariance.java
an Object[] view of a String[]: 2 elements
ArrayStoreException: java.lang.Integer
names[0] is still ana
$ java Invariance.java
Invariance.java:7: error: incompatible types: List<String> cannot be converted to List<Object>
        List<Object> objects = names;
                               ^
1 error
error: compilation failed
What’s happening
  1. Object[] objects = names; compiles: arrays are covariant, so a String[] is an Object[]. Both variables point at the same array.
  2. objects[0] = 42 also compiles, since you can put an Integer into an Object[]. But the array object remembers it was created as a String[], and the JVM checks every store into it: ArrayStoreException: java.lang.Integer. The array is unchanged, names[0] is still ana.
  3. The generic version fails earlier. List<Object> objects = names; doesn't compile ("incompatible types"), because generics are invariant, so the bad add never gets the chance to run.
  4. That's the trade: arrays find the mistake at run time, generics at compile time. It's also why new T[] is forbidden: an array needs its element class at run time to make this check, and with erasure T doesn't have one.
Where does the exception happen?
Pollution.java
import java.util.ArrayList;
import java.util.List;

public class Pollution {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        List raw = numbers;
        raw.add("seven");

        System.out.println("size " + numbers.size());
        System.out.println("contents " + numbers);
        Object first = numbers.get(0);
        System.out.println("first " + first);
        int n = numbers.get(0);
        System.out.println("n " + n);
    }
}
Show answer
Terminal
$ java Pollution.java
size 1
contents [seven]
first seven
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
	at Pollution.main(Pollution.java:15)
What’s happening
  1. List raw = numbers; is a raw view of the same list. Through it, the compiler doesn't check the element type, so raw.add("seven") puts a String into a List<Integer>. That's heap pollution, and nothing fails yet: at run time the list is just an ArrayList of Objects.
  2. numbers.size() is 1 and printing the list calls each element's toString: contents [seven]. Still no error.
  3. Object first = numbers.get(0); doesn't fail either: the value goes into an Object variable, so the compiler has no need to insert a cast to Integer.
  4. int n = numbers.get(0); needs an Integer (to unbox it), so here the compiler's hidden checkcast runs and fails: ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer. The run ends there, on purpose.
  5. The exception is four lines away from the bug, and in a real program it could be in another class. @SuppressWarnings("unchecked") hid the warning that would have pointed at raw.add; only suppress a warning when you've proved it's safe.
AdvancedUnchecked warnings and primitives
Warnings.java
import java.util.ArrayList;
import java.util.List;

public class Warnings {
    public static void main(String[] args) {
        List raw = new ArrayList();
        raw.add("x");
        List<Integer> numbers = raw;
        System.out.println(numbers.size());
    }
}
Primitive.java
import java.util.List;

public class Primitive {
    public static void main(String[] args) {
        List<int> numbers = List.of(1, 2, 3);
    }
}
Terminal
$ javac Warnings.java
Note: Warnings.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javac -Xlint:unchecked Warnings.java
Warnings.java:7: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
        raw.add("x");
               ^
  where E is a type-variable:
    E extends Object declared in interface List
Warnings.java:8: warning: [unchecked] unchecked conversion
        List<Integer> numbers = raw;
                                ^
  required: List<Integer>
  found:    List
2 warnings
$ java Warnings
1
$ javac Primitive.java
Primitive.java:5: error: unexpected type
        List<int> numbers = List.of(1, 2, 3);
             ^
  required: reference
  found:    int
1 error
What’s happening
  1. By default javac only prints a summary Note: that the file uses unchecked or unsafe operations, and compiles anyway. Easy to miss in a long build log.
  2. -Xlint:unchecked shows each warning on its line: the unchecked call to add on the raw type, and the unchecked conversion when the raw List is assigned to List<Integer>. In Maven you'd turn these on in the compiler plugin's settings (chapter 11), and many teams fail the build on warnings.
  3. java Warnings runs and prints 1: warnings don't stop anything. The list now holds a String behind a List<Integer> variable, waiting to fail later.
  4. List<int> is a hard error: type arguments must be reference types, and the compiler says it expected a reference and found int. Use List<Integer>, or an int[] or IntStream when boxing every number costs too much.

#Your turn: generics

Added
Your turn: a generic Pair and an inverted map

Write a generic record Pair<A, B> with a swap() method that returns a Pair<B, A>, and a generic method invert(Map<K, V>) that returns a Map<V, K>. Use them on Pair("java", 25) and on a map of language names to versions.

Show answer
Pairs.java
record Pair<A, B>(A first, B second) {
    Pair<B, A> swap() {
        return new Pair<>(second, first);
    }
}

static <K, V> Map<V, K> invert(Map<K, V> map) {
    var inverted = new LinkedHashMap<V, K>();
    for (var entry : map.entrySet()) {
        inverted.put(entry.getValue(), entry.getKey());
    }
    return inverted;
}

void main() {
    Pair<String, Integer> pair = new Pair<>("java", 25);
    Pair<Integer, String> swapped = pair.swap();
    IO.println(pair + " -> " + swapped);

    var versions = new LinkedHashMap<String, Integer>();
    versions.put("java", 25);
    versions.put("node", 24);
    Map<Integer, String> byVersion = invert(versions);
    IO.println(byVersion + ", 24 is " + byVersion.get(24));
}
Terminal
$ java Pairs.java
Pair[first=java, second=25] -> Pair[first=25, second=java]
{25=java, 24=node}, 24 is node
What’s happening
  1. Pair<A, B> has two type parameters. swap() returns Pair<B, A>: the types swap along with the values, and new Pair<>(second, first) lets the diamond infer them from the return type.
  2. pair.swap() on a Pair<String, Integer> is a Pair<Integer, String>, so the result goes into that variable with no cast: Pair[first=java, second=25] -> Pair[first=25, second=java].
  3. invert declares <K, V> before its return type and swaps them in the result. A LinkedHashMap keeps insertion order, so the output is predictable: {25=java, 24=node}.
  4. byVersion.get(24) is typed as String: node. If two keys had the same value, the later one would win, which a real invert should check for.
Your turn: one max for every comparable type

Write maxOf(Collection<? extends T> items) with the most general bound, so it works for List<Integer>, List<String> and for a List<Release> where only the parent class Version implements Comparable<Version>. It should throw IllegalArgumentException for an empty collection.

Show answer
MaxOf.java
import java.util.Collection;
import java.util.List;

public class MaxOf {
    static <T extends Comparable<? super T>> T maxOf(Collection<? extends T> items) {
        if (items.isEmpty()) {
            throw new IllegalArgumentException("no items");
        }
        T best = null;
        for (T item : items) {
            if (best == null || item.compareTo(best) > 0) {
                best = item;
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxOf(List.of(3, 11, 7)));
        System.out.println(maxOf(List.of("kiwi", "fig", "plum")));
        System.out.println(maxOf(List.of(new Release(21), new Release(25), new Release(17))));
        try {
            maxOf(List.<Integer>of());
        } catch (IllegalArgumentException e) {
            System.out.println("empty: " + e.getMessage());
        }
    }
}

class Version implements Comparable<Version> {
    final int number;

    Version(int number) {
        this.number = number;
    }

    @Override
    public int compareTo(Version other) {
        return Integer.compare(number, other.number);
    }

    @Override
    public String toString() {
        return "Java " + number;
    }
}

class Release extends Version {
    Release(int number) {
        super(number);
    }
}
Terminal
$ java MaxOf.java
11
plum
Java 25
empty: no items
What’s happening
  1. T extends Comparable<? super T> accepts any T that can be compared by itself or by a supertype, which is what makes Release work: it inherits compareTo(Version).
  2. Collection<? extends T> is a producer: the method only reads from it, so a List<Release> is accepted where T = Release (or a list of any subtype of T).
  3. The loop keeps the largest so far, comparing with compareTo: 11, plum (alphabetically last) and Java 25.
  4. List.<Integer>of() uses a type witness to make an empty List<Integer>; the method throws, and the catch prints empty: no items.
  5. This is the same shape as the JDK's Collections.max, minus its extra Object & in the bound. That part changes only the erasure: the class file's descriptor for Collections.max is (Ljava/util/Collection;)Ljava/lang/Object;, the same as the method had before generics (Collections dates from Java 1.2), so code compiled against the old version kept working.
Your turn: PECS in one method

Write moveAll(source, target) that moves every element out of a source list into a target list, so you can move a List<Integer> into a List<Number> or a List<Object>, but the compiler stops you moving a List<Number> into a List<Integer>.

Show answer
Move.java
static <T> void moveAll(List<? extends T> source, List<? super T> target) {
    target.addAll(source);
    source.clear();
}

void main() {
    List<Integer> ints = new ArrayList<>(List.of(1, 2, 3));
    List<Number> numbers = new ArrayList<>(List.of(0.5));
    List<Object> objects = new ArrayList<>(List.of("start"));

    moveAll(ints, numbers);
    IO.println("ints " + ints + ", numbers " + numbers);

    moveAll(numbers, objects);
    IO.println("numbers " + numbers + ", objects " + objects);
}
Backwards.java
static <T> void moveAll(List<? extends T> source, List<? super T> target) {
    target.addAll(source);
    source.clear();
}

void main() {
    List<Number> numbers = new ArrayList<>(List.of(0.5));
    List<Integer> ints = new ArrayList<>();
    moveAll(numbers, ints);
}
Terminal
$ java Move.java
ints [], numbers [0.5, 1, 2, 3]
numbers [], objects [start, 0.5, 1, 2, 3]
$ java Backwards.java
Backwards.java:9: error: method moveAll in class Backwards cannot be applied to given types;
    moveAll(numbers, ints);
    ^
  required: List<? extends T>,List<? super T>
  found:    List<Number>,List<Integer>
  reason: inference variable T has incompatible bounds
    upper bounds: Integer,Object
    lower bounds: Number
  where T is a type-variable:
    T extends Object declared in method <T>moveAll(List<? extends T>,List<? super T>)
1 error
error: compilation failed
What’s happening
  1. source only produces elements (? extends T) and target only consumes them (? super T): PECS. T is the element type in between, inferred at each call.
  2. moveAll(ints, numbers) infers a T that Integer extends and Number is a super of (Integer or Number both work). The integers are added after 0.5 and ints is emptied: ints [], numbers [0.5, 1, 2, 3].
  3. moveAll(numbers, objects) works the same way with T = Number: numbers [], objects [start, 0.5, 1, 2, 3].
  4. Backwards.java tries moveAll(numbers, ints). That needs a T that is a supertype of Number (to read from the source) and a subtype of Integer (to write into the target). No such type exists, so the compiler refuses the call: a 0.5 can never end up in a List<Integer>. That's the protection invariance gives you, with the flexibility wildcards add back.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.