首页 > 解决方案 > 为什么 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。

有人可以解释一下吗?

标签: javacollectionscasting

解决方案


我没有测试过这个,但我认为这有效。更改方法参数的类型:

public static double arithmeticMean(Collection<Number> collection) {

public static double arithmeticMean(Collection<? extends Number> collection) {

编辑:由于这有效,请阅读什么是 PECS?. 它将帮助您更多地了解何时以及如何使用通用通配符。


推荐阅读