Key points
- Generics move type checking to compile time:
add(7)on aList<String>fails to compile; without generics the mistake only shows up at run time as aClassCastException. - Generic classes:
class Result<T>; T is fixed when the object is created, and several type parameters are writtenPair<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 inpublic 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 aList<Object>, or the latter could be used to put non-String elements into it.
Code and examples
1 | public class Result<T> { |
Further notes
- Arrays are covariant (a
String[]can be assigned to anObject[]), at the cost of anArrayStoreExceptionat 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).
Related
- 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 | public class Result<T> { |
延伸
- 数组是协变的(
String[]可赋给Object[]),代价是运行时ArrayStoreException;泛型选择编译期拦截。 - 想接收各种
List<X>需用通配符? extends/? super(下一张卡)。
相关
- 下一张卡:Java 泛型-类型擦除、Java 泛型-通配符