I want to compute the arithmetic mean of any Collection of Integers or Doubles.
I have defined the following method:
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");
}
To test the method, I create an ArrayList of Double, as follows:
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;
}
But when I invoke the arithmeticMean method like this:
public static void main(String[] args) {
System.out.println(arithmeticMean(dataSet));
System.out.println(arithmeticMean((Collection<Number>) dataSet));
}
The first invocation results in the error:
The method arithmeticMean(Collection<Number>) in the type SimpleStats is not applicable for the arguments (ArrayList<Double>)
And the second invocation results in the error:
Cannot cast from ArrayList<Double> to Collection<Number>
After reading the Oracle Java Tutorials section on Collections, I do not understand why I can't pass an ArrayList object to a method expecting a Collection. ArrayList inherits from Collection and Double inherits from Number.
Can someone please explain?