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.
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
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.
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
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 Tfor a collection you only read from, and? super Tfor one you only write to.Collections.copy(dest, src)is the classic example. - Invariance:
List<Integer>is not a subtype ofList<Number>, althoughInteger[]is a subtype ofNumber[](arrays are covariant, with runtime checks that can throwArrayStoreException). - 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 (
Listwithout 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.
varwith diamond (var list = new ArrayList<>()) infersArrayList<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 Exceptiondoes not compile), andcatch (T e)is illegal. - Heap pollution and varargs: generic varargs (
T...) create an array of a non-reifiable type and produce warnings;@SafeVarargssuppresses them onstatic,final, andprivatemethods when you are sure.