请参见以下代码:
public class GenericsMethod {
// As per my understanding this will accept any list which extends Number
public double sum(List<? extends Number> list){
double sum = 0;
for(Number n : list){
sum += n.doubleValue();
}
return sum;
}
// As per my understanding this will accept any list which is extended by Integer, e.g Number
public Integer addIntegers(List<? super Integer> list){
return sum(list); // does not allow me
}
public static void main(String[] args){
//I am sending the same type of list to two different methods.
List<Number> l = new ArrayList<>();
l.add(1);
l.add(2);
l.add(4);
l.add(5);
System.out.println(m.sum(l));
List<Number> numL = new ArrayList<>();
numL.add(1);
numL.add(2);
numL.add(4);
numL.add(5);
System.out.println(m.addIntegers(numL));
}
}
错误消息如下:
Error:(27, 15) java: method sum in class com.learning.Generics.GenericsMethod cannot be applied to given types;
required: java.util.List<? extends java.lang.Number>
found: java.util.List<capture#1 of ? super java.lang.Integer>
reason: actual argument java.util.List<capture#1 of ? super java.lang.Integer> cannot be converted to java.util.List<? extends java.lang.Number> by method invocation conversion
请更正我的理解。我的问题是我将相同类型的列表发送给两种不同的方法。为什么不允许我通过addIntegers()调用sum()方法?