6

I have following two methods:

public static double calculateMeanInt(List<Integer> numbers) {
    double sum = 0.0;
    for(Integer number : numbers)
        sum += number;
    return sum/numbers.size();
}

public static double calculateMeanDouble(List<Double> numbers) {
    double sum = 0.0;
    for(Double number : numbers)
        sum += number;
    return sum/numbers.size();
}

Do you have an elegant solution (other than using type casting and Object) that will avoid the duplicate code above and will use a single method name?

1 Answer 1

13

Each numeric type in Java extends from Number, so you can use the bounded type parameter (thanks Paul) to average all your number types in one method:

  public static <N extends Number> double calculateMean(List<N> numbers) {
    double sum = 0.0;
    for (N number : numbers)
      sum += number.doubleValue();
    return sum / numbers.size();
  }

e.G. like that:

double intMean = calculateMean(Lists.newArrayList(1,2,3,4,5));
double doubleMean = calculateMean(Lists.newArrayList(1d,2d,3d,4d,5d));
double longMean = calculateMean(Lists.newArrayList(1l,2l,3l,4l,5l));

Note that Lists is part of Guava.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Nice answer. Nitpick: this is a bounded type parameter - a bounded wildcard would look like List<? extends Number> numbers (in this case it would behave the same).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.