我在 countList 方法上遇到编译时错误。
public static void countList( List<? extends Number> list, int count ){
for( int i = 0; i < count; i++ ){
list.set(i, i-1);
}
}
public static void clearList( List<?extends Number> list){
list.clear();
}
它说: List 类型中的方法 set(int, capture#2-of ? extends Number) 不适用于参数 (int, int)
这个错误信息是什么意思?为什么我无法设置列表中的元素?为什么清空列表就可以了?
最佳答案
因为它是一个“扩展数字的东西,但我不知道是什么”的列表。你不能只把整数放在那里,如果它实际上是一个 double 列表怎么办?
List<Double> list = new ArrayList<Double>();
list.add(Double.valueOf(4.5);
countList(list, 1);
Double d = list.get(0); //what happens here? You put an Integer in there! class cast exception
您可以清除列表,因为对于该操作,实际上其中的 Number 子类型并不重要。清楚是清楚是清楚。
关于java - 通配符,java中的通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11112062/