问题是由于类型擦除,编译器不知道在运行时将哪种类型的 Number 添加到列表中。考虑这个例子:
public static void main(String[] args) {
List<Integer> intList= new ArrayList<Integer>();
// add some Integers to the list here
countList(intList, 4);
}
public static void countList( List<? extends Number> list, int count ) {
for( double d = 0.0; d < count; d++ ){
list.set((int)d, d-1); // problem at d-1, because at runtime,
// the double result of d-1 will be autoboxed to a Double,
// and now you have added a Double to an Integer List (yikes!);
}
}
因此,您永远无法使用该语法添加到通用类型的集合中。? extends SomeObject
如果必须添加,可以将方法声明更改为:
- 将方法声明更改为
public static void countList( List<Number> list, int count )
- 将方法更改为
public static void countList( List<? super Integer> list, int count )
.
无论哪种方式,编译器都会停止抱怨,因为它可以放心,您永远不会在 List 中添加与声明的 List 不同类型的任何内容。