我有这个通用函数:
public static <T extends Number> T sum(List<T> list){
Number tot = 0;
for(Number n: list){
tot = tot.doubleValue() + n.doubleValue();
}
return (T)tot;
}
从这个代码中回忆起主函数:
public static void main(String[] args) {
ArrayList<Integer> listInt = new ArrayList<>();
listInt.add(3);
listInt.add(5);
listInt.add(6);
listInt.add(8);
System.err.println("Sum: " + Calcolatrice.sum(listInt))
}
因此,我期望(listInt 是一个整数ArrayList)函数sum返回的值为T = Integer,并且在这种情况下,将Double转换为Integer时会出现转换错误。 结果类型实际上是Double,没有抛出错误。 强制转换(T)tot没有产生预期的结果。
我猜这是因为Java处理泛型的阶段问题,但其中有人更好地解释为什么会这样工作吗?