java - 为什么 Java 不使用 ArrayList对象作为集合目的?
问题描述
我想计算任何整数或双精度集合的算术平均值。
我定义了以下方法:
public static double arithmeticMean(Collection<Number> collection) {
for(Number element : collection)
if (element.getClass().isInstance(Integer.class)) {
Collection<Integer> intCollection = new ArrayList<>();
for(Number number : collection)
intCollection.add(number.intValue());
return arithmeticMeanOfIntegers(intCollection);
} else if (element.getClass().isInstance(Double.class)) {
Collection<Double> doubleCollection = new ArrayList<>();
for(Number number : collection)
doubleCollection.add(number.doubleValue());
return arithmeticMeanOfDoubles(doubleCollection);
}
throw new IllegalArgumentException("Method 'arithmeticMean' only operates on integer or double types");
}
为了测试该方法,我创建了一个 Double 的 ArrayList,如下所示:
private static ArrayList<Double> dataSet = getDataSet();
private static ArrayList<Double> getDataSet() {
ArrayList<Double> dataSet = new ArrayList<>();
for(int i = 1; i < 21; i++)
dataSet.add(new Double(i));
return dataSet;
}
但是当我像这样调用算术平均方法时:
public static void main(String[] args) {
System.out.println(arithmeticMean(dataSet));
System.out.println(arithmeticMean((Collection<Number>) dataSet));
}
第一次调用导致错误:
The method arithmeticMean(Collection<Number>) in the type SimpleStats is not applicable for the arguments (ArrayList<Double>)
第二次调用导致错误:
Cannot cast from ArrayList<Double> to Collection<Number>
在阅读了关于集合的 Oracle Java 教程部分后,我不明白为什么我不能将 ArrayList 对象传递给期望集合的方法。ArrayList 继承自 Collection,Double 继承自 Number。
有人可以解释一下吗?
解决方案
我没有测试过这个,但我认为这有效。更改方法参数的类型:
public static double arithmeticMean(Collection<Number> collection) {
至
public static double arithmeticMean(Collection<? extends Number> collection) {
编辑:由于这有效,请阅读什么是 PECS?. 它将帮助您更多地了解何时以及如何使用通用通配符。
推荐阅读
- java - Optional OneToOne relation in Hibernate
- c++ - GDB:同时调试2个进程
- android - Cannot intercept touch on overlay service
- mysql - MYSQL在一分钟内发现重复
- .net - 运行时创建不同的 EDMX 模型
- python - 在 Python 中创建不可变对象
- flutter - 我不能使用 Icon(Icons.star, color: Colors.green[500]),错误
- wordpress - 单击后可以从 $_SESSION 存储值
- amazon-web-services - 如何在 Cloudformation 模板条件中使用 AWS SSM 参数存储值?
- vue.js - 如何在 Vue 中将组件的整个数据属性设置为保持反应性的新对象?