Java Generics 简明教程
Java Generics - No Cast
不允许强制转换为参数化类型,除非该类型由无界通配符参数化。
Box<Integer> integerBox = new Box<Integer>();
Box<Number> numberBox = new Box<Number>();
//Compiler Error: Cannot cast from Box<Number> to Box<Integer>
integerBox = (Box<Integer>)numberBox;
要达到同样的效果,可以使用无界通配符。
private static void add(Box<?> box) {
Box<Integer> integerBox = (Box<Integer>)box;
}