Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Keywords and Statements

Java generics syntax

Reference for Java generics syntax: type parameters, generic classes and methods, bounds, wildcards, the diamond operator and what erasure means for you.

Generics let a class, interface, or method work with types that are named by the caller instead of being fixed in the source. You declare type parameters in angle brackets, and the compiler checks every use, so a List<String> can only hold strings and get() returns a String without a cast.

Generics exist only at compile time. The compiler checks types and then erases them (type erasure), which is why some things, such as new T() or instanceof List<String>, are not allowed.

Java
class Box<T> {                       // generic class, T is a type parameter
    private T value;
    void set(T v) { value = v; }
    T get() { return value; }
}

static <T extends Comparable<T>> T max(T a, T b) {   // generic method with a bound
    return a.compareTo(b) >= 0 ? a : b;
}

List<? extends Number> readOnly;     // wildcard
Box<String> b = new Box<>();         // diamond operator

Try it

Java Generic classes and methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Wildcards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
class Name<T, U extends Bound> { ... }
interface Name<T> { ... }
<T> ReturnType method(T arg) { ... }
<T extends A & B> void method(T arg) { ... }
Form Meaning
<T> Type parameter, any reference type.
<T extends Number> Upper bound: T must be Number or a subtype.
<T extends A & B> Multiple bounds; at most one class, listed first, then interfaces.
List<?> Unbounded wildcard: a list of some unknown type.
List<? extends T> Upper-bounded wildcard: elements are read as T.
List<? super T> Lower-bounded wildcard: you may add T.
new Box<>() Diamond: the compiler infers the type arguments.
Util.<String>make() Explicit type arguments for a generic method call.

Primitive types cannot be type arguments; use Integer, Long, Double, and so on, or primitive-specialized types such as IntStream.

Usage notes

  • PECS: "Producer Extends, Consumer Super". Use ? extends T for a collection you only read from, and ? super T for one you only write to. Collections.copy(dest, src) is the classic example.
  • Invariance: List<Integer> is not a subtype of List<Number>, although Integer[] is a subtype of Number[] (arrays are covariant, with runtime checks that can throw ArrayStoreException).
  • Erasure consequences: you cannot write new T(), new T[10], T.class, x instanceof List<String>, or overload two methods that differ only in type arguments. Static members cannot use the class's type parameters.
  • Raw types (List without arguments) disable checking and exist only for compatibility. Avoid them; an unchecked warning means the compiler can no longer vouch for your types.
  • Diamond with anonymous classes is allowed since Java 9. var with diamond (var list = new ArrayList<>()) infers ArrayList<Object>, which is rarely intended.
  • Static generic methods put the type parameter before the return type: static <T> List<T> listOf(T a).
  • Naming: single capital letters by convention: T (type), E (element), K/V (key/value), R (result), N (number).
  • Generic exceptions are not allowed (class MyEx<T> extends Exception does not compile), and catch (T e) is illegal.
  • Heap pollution and varargs: generic varargs (T...) create an array of a non-reifiable type and produce warnings; @SafeVarargs suppresses them on static, final, and private methods when you are sure.