Key points

  • Generics move type checking to compile time: add(7) on a List<String> fails to compile; without generics the mistake only shows up at run time as a ClassCastException.
  • Generic classes: class Result<T>; T is fixed when the object is created, and several type parameters are written Pair<K, V>. Once T is fixed, so are the constructor’s parameter types: new Result<String>(123, "ok") does not compile, because 123 is not a String.
  • Generic methods: <T> goes before the return type, as in public static <T> void swap(T[] arr, int i, int j); the compiler infers T at each call.
  • Generics are invariant: a List<String> cannot be assigned to a List<Object>, or the latter could be used to put non-String elements into it.

Code and examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Result<T> {
private T data;
private String message;

public Result(T data, String message) {
this.data = data;
this.message = message;
}

public T getData() { return data; }
}

Result<Integer> r = new Result<>(200, "ok");
int code = r.getData();

Further notes

  • Arrays are covariant (a String[] can be assigned to an Object[]), at the cost of an ArrayStoreException at run time; generics chose to stop the mistake at compile time.
  • To accept any kind of List<X>, use the wildcards ? extends / ? super (the next card).
  • Next cards: Java Generics: Type Erasure, Java Generics: Wildcards

要点

  • 泛型把类型检查提前到编译时:List<String> 里 add(7) 编译就报错;没有泛型时要到运行时才抛 ClassCastException。
  • 泛型类:class Result<T>,创建时确定 T;多个类型参数写成 Pair<K, V>。T 确定后,构造器参数类型也随之确定,new Result<String>(123, "ok") 因 123 不是 String 而编译失败。
  • 泛型方法:<T> 写在返回类型前,如 public static <T> void swap(T[] arr, int i, int j);T 每次调用时由编译器推断。
  • 泛型不协变:List<String> 不能赋给 List<Object>,否则可借后者塞入非 String 元素。

代码与例句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Result<T> {
private T data;
private String message;

public Result(T data, String message) {
this.data = data;
this.message = message;
}

public T getData() { return data; }
}

Result<Integer> r = new Result<>(200, "ok");
int code = r.getData();

延伸

  • 数组是协变的(String[] 可赋给 Object[]),代价是运行时 ArrayStoreException;泛型选择编译期拦截。
  • 想接收各种 List<X> 需用通配符 ? extends / ? super(下一张卡)。

相关

  • 下一张卡:Java 泛型-类型擦除、Java 泛型-通配符