Skills101

AdvancedJava Programming · Lesson 19 of 29 · Updated ·

Generics in Java — Generic Classes, Methods, Bounded Types and Wildcards

You have used generics every time you wrote List<String> or Map<String, Integer>. The part in angle brackets is a type parameter: it tells the compiler what type the collection holds, so mistakes are caught when you compile instead of crashing when the program runs. This lesson shows how to write your own generic classes and methods and explains the rules that confuse most students — wildcards and type erasure.

1. The problem generics solve

Before Java 5, a list held plain Objects. You could put anything in, and you had to cast when taking things out:

import java.util.*;

public class Main {
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void main(String[] args) {
        List marks = new ArrayList();          // raw type: no type parameter
        marks.add(90);
        marks.add("eighty");                   // compiler does not complain
        try {
            int total = 0;
            for (Object m : marks) total += (Integer) m;   // cast needed
            System.out.println(total);
        } catch (ClassCastException e) {
            System.out.println("Crash at runtime: " + e.getClass().getSimpleName());
        }

        List<Integer> safe = new ArrayList<>();
        safe.add(90);
        // safe.add("eighty");                 // compile error: caught before running
        int first = safe.get(0);               // no cast needed
        System.out.println(first);
    }
}
Crash at runtime: ClassCastException
90

With List<Integer>, the wrong add is a compile error, and no cast is needed when reading. That is the whole point of generics: type safety + no casts.

2. Writing a generic class

Put a type parameter after the class name. By convention it is one capital letter: T (type), E (element), K and V (key and value).

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; }

    @Override
    public String toString() { return "(" + key + ", " + value + ")"; }
}

public class Main {
    public static void main(String[] args) {
        Pair<String, Integer> rank = new Pair<>("Asha", 1);
        Pair<String, Double> cgpa = new Pair<>("Ravi", 8.6);
        String name = rank.getKey();          // compiler knows it is a String
        int position = rank.getValue();       // and this is an Integer
        System.out.println(name + " is rank " + position);
        System.out.println(rank + " " + cgpa);
    }
}
Asha is rank 1
(Asha, 1) (Ravi, 8.6)

One Pair class works for any two types, and each use is fully type-checked. The <> on the right (the diamond) lets the compiler fill in the types from the left side.

3. Generic methods

A method can have its own type parameter, written before the return type. The compiler works out T from the arguments (this is called type inference).

import java.util.*;

public class Main {
    static <T> T lastOrDefault(List<T> list, T fallback) {
        return list.isEmpty() ? fallback : list.get(list.size() - 1);
    }

    static <T> void swap(T[] arr, int i, int j) {
        T tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void main(String[] args) {
        System.out.println(lastOrDefault(List.of("Pune", "Delhi"), "none"));
        System.out.println(lastOrDefault(new ArrayList<Integer>(), -1));

        String[] seats = {"A1", "B2", "C3"};
        swap(seats, 0, 2);
        System.out.println(Arrays.toString(seats));
    }
}
Delhi
-1
[C3, B2, A1]

4. Bounded type parameters

Sometimes T must be "some kind of number" or "something that can be compared". A bound says so: <T extends Number> or <T extends Comparable<T>>. Inside the method you may then call the bound's methods.

import java.util.*;

public class Main {
    static <T extends Comparable<T>> T max(List<T> items) {
        T best = items.get(0);
        for (T x : items) {
            if (x.compareTo(best) > 0) best = x;     // allowed: T is Comparable
        }
        return best;
    }

    static <T extends Number> double average(List<T> nums) {
        double sum = 0;
        for (T n : nums) sum += n.doubleValue();    // allowed: T is a Number
        return sum / nums.size();
    }

    public static void main(String[] args) {
        System.out.println(max(List.of(42, 97, 15)));
        System.out.println(max(List.of("mango", "apple", "kiwi")));
        System.out.println(average(List.of(70, 85, 90)));
        System.out.println(average(List.of(7.5, 8.5)));
        // average(List.of("a"));  ← compile error: String is not a Number
    }
}
97
mango
81.66666666666667
8.0

In a bound, extends is used for both classes and interfaces.

5. Wildcards: ? extends and ? super

Here is the rule that surprises everyone: an Integer is a Number, but a List<Integer> is not a List<Number>. If it were, you could do this:

List<Integer> ints = new ArrayList<>();
List<Number> nums = ints;      // suppose this were allowed…
nums.add(3.14);                // …a Double would now sit inside a list of Integers

So Java refuses. To write a method that accepts lists of different number types, use a wildcard ?.

Wildcards: List<? extends Number> accepts List<Integer>, List<Double> and List<Number> and is safe to read Numbers from; List<? super Integer> accepts List<Integer>, List<Number> and List<Object> and is safe to add Integers to

WildcardAcceptsYou can safelyThink
List<? extends Number>List<Integer>, List<Double>, List<Number>read items as Numberproducer (gives you items)
List<? super Integer>List<Integer>, List<Number>, List<Object>add Integersconsumer (takes your items)
List<?>any listread items as Object"I don't care about the type"

The memory aid is PECS: Producer Extends, Consumer Super.

import java.util.*;

public class Main {
    static double total(List<? extends Number> list) {      // producer: we only read
        double sum = 0;
        for (Number n : list) sum += n.doubleValue();
        return sum;
    }

    static void addRollNumbers(List<? super Integer> list) { // consumer: we only add
        for (int i = 1; i <= 3; i++) list.add(i);
    }

    public static void main(String[] args) {
        List<Integer> ints = List.of(10, 20);
        List<Double> prices = List.of(99.5, 0.5);
        System.out.println(total(ints) + " " + total(prices));

        List<Number> numbers = new ArrayList<>();
        List<Object> objects = new ArrayList<>();
        addRollNumbers(numbers);
        addRollNumbers(objects);
        System.out.println(numbers + " " + objects);
    }
}
30.0 100.0
[1, 2, 3] [1, 2, 3]

Java's own library follows PECS: Collections.copy(List<? super T> dest, List<? extends T> src).

6. Type erasure

Generics exist only at compile time. After checking types, the compiler erases them: List<String> and List<Integer> both become a plain List in the bytecode, and the compiler inserts the casts for you. This kept new code compatible with old, pre-generics code.

Type erasure: at compile time List<String> and List<Integer> are different checked types; after compiling, both become a plain List in the bytecode and the compiler adds the casts

import java.util.*;

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

Because of erasure:

  • You cannot use primitives: List<int> is an error — use List<Integer>.
  • You cannot write new T() or new T[10] — at runtime there is no T.
  • You cannot check x instanceof List<String> — only x instanceof List<?>.
  • Two methods void f(List<String>) and void f(List<Integer>) clash — after erasure both are f(List).

Common mistakes

  • Using raw types (List list = new ArrayList();) and losing all type checking.
  • Expecting List<Integer> to be passed where List<Number> is required — use List<? extends Number>.
  • Trying to add to a List<? extends Number>. You can only read from it (except null).
  • Writing List<int> or new T().
  • Over-using wildcards in return types; return a concrete type like List<T> so callers can use it easily.

Quick recap

  • Generics move type errors from runtime to compile time and remove casts.
  • Generic class: class Box<T>; generic method: static <T> T f(...).
  • Bounds: <T extends Number>, <T extends Comparable<T>> let you call the bound's methods.
  • List<Integer> is not a List<Number>. PECS: ? extends to read, ? super to add.
  • Type erasure: generic types vanish at runtime, so no primitives, no new T(), no instanceof List<String>.

Practice what you learned

📝 Quiz: Java Generics5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →