Reading history

Java Generics: Generic Classes, Methods and Wildcards

5 min read 0 views

Learn Java generics: type parameters, generic classes and methods, bounded types, wildcards with extends and super (PECS), and type erasure.

Generics let you write a class or method once and use it safely with many types. When you write List<String>, you are using generics: the compiler knows the list holds only strings, rejects anything else, and removes the need for casts. This lesson shows how to write your own generic classes and methods, how bounds and wildcards work, and what type erasure means.

In this lesson you will learn

  • Why generics exist: type safety without casts
  • Generic classes such as Box<T> and Pair<K, V>
  • Generic methods
  • Bounded types with extends
  • Wildcards ?, ? extends and ? super

Generic Classes and Methods

import java.util.List;

class Box<T> {                         // T is a type parameter
    private T value;
    Box(T value) { this.value = value; }
    T get() { return value; }
    void set(T value) { this.value = value; }
}

class Pair<K, V> {
    final K key; final V value;
    Pair(K key, V value) { this.key = key; this.value = value; }
    public String toString() { return "(" + key + ", " + value + ")"; }
}

public class Main {
    // Generic method: works for a list of any type
    static <T> T firstOrDefault(List<T> list, T fallback) {
        return list.isEmpty() ? fallback : list.get(0);
    }

    public static void main(String[] args) {
        Box<String> name = new Box<>("Nadia");
        Box<Integer> age = new Box<>(21);
        String n = name.get();               // no cast needed
        int a = age.get() + 1;               // auto-unboxing
        System.out.println(n + " will be " + a);
        // name.set(42);                     // compile error: wrong type

        Pair<String, Double> p = new Pair<>("cgpa", 3.82);
        System.out.println(p);
        System.out.println(firstOrDefault(List.of(5, 9), -1));
        System.out.println(firstOrDefault(List.<String>of(), "none"));
    }
}

Output

Nadia will be 22
(cgpa, 3.82)
5
none
  • class Box<T> declares a type parameter T. It is a placeholder that becomes a real type when the class is used, such as Box<String>.
  • Because the compiler knows name holds a String, name.get() needs no cast, and name.set(42) would be rejected at compile time rather than failing later at run time.
  • A class can have several parameters: Pair<K, V>. Common names are T (type), E (element), K and V (key and value).
  • A generic method declares its own type parameter before the return type: static <T> T firstOrDefault(...). Java usually infers T from the arguments.
  • Type parameters must be reference types: Box<int> is not allowed, but Box<Integer> is, and autoboxing converts values for you.

Bounded Types and Wildcards

import java.util.List;

public class Main {
    // Bounded type: T must be a Comparable of itself
    static <T extends Comparable<T>> T largest(List<T> items) {
        T best = items.get(0);
        for (T x : items) if (x.compareTo(best) > 0) best = x;
        return best;
    }

    // Upper-bounded wildcard: read numbers of any Number subtype
    static double sum(List<? extends Number> nums) {
        double s = 0;
        for (Number x : nums) s += x.doubleValue();
        return s;
    }

    public static void main(String[] args) {
        System.out.println(largest(List.of(4, 17, 9)));
        System.out.println(largest(List.of("pear", "apple", "mango")));
        System.out.println(sum(List.of(1, 2, 3)));
        System.out.println(sum(List.of(1.5, 2.25)));
    }
}

Output

17
pear
6.0
3.75
  • <T extends Comparable<T>> is a bounded type: T can be any type that can be compared with itself, so the method may call compareTo. It works for integers and strings alike.
  • List<? extends Number> accepts a list of Integer, Double or any other Number subtype. You can read elements as Number, but you cannot add to such a list.
  • A List<Integer> is not a List<Number>, even though Integer is a Number. Wildcards exist to bridge this gap.
SyntaxMeaningTypical use
List<?>A list of some unknown typePrinting or counting any list
List<? extends T>T or a subtypeReading values out (a producer)
List<? super T>T or a supertypeWriting values in (a consumer)

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

Type Erasure

Generics are checked by the compiler and then removed from the compiled code; at run time a List<String> and a List<Integer> are both just List. As a result you cannot write new T(), new T[10] or obj instanceof List<String>.

Common Mistakes

  1. Using raw types such as List list = new ArrayList();, which turns off type checking and causes warnings.
  2. Expecting List<Integer> to be accepted where List<Number> is required; use List<? extends Number>.
  3. Using primitives as type arguments.
  4. Trying to create new T(), which erasure makes impossible.

Practice Exercises

Exercise 1. Write a generic method swap that swaps two elements of an array of any reference type.

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

Exercise 2. Write a method that counts the elements of any list, whatever its type.

Show answer
static int count(List<?> list) {
    int n = 0;
    for (Object o : list) n++;
    return n;
}

Frequently Asked Questions

What is the diamond operator?

The empty angle brackets in new ArrayList<>(). Since Java 7 the compiler infers the type arguments from the variable’s declared type.

Do generics slow programs down?

No. Thanks to erasure, generic code compiles to the same bytecode as code that uses casts, so there is no run-time cost.

Summary

  • Generics move type errors from run time to compile time and remove casts.
  • Declare type parameters on classes (Box<T>) or methods (<T> T f()).
  • Bounds such as T extends Comparable<T> unlock methods on T.
  • Wildcards make APIs flexible: producer extends, consumer super.

Next: Java Enums and Records.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *