Home » Java » Method Overloading and Arguments with Generics in Java

Method Overloading and Arguments with Generics in Java

Posted by: admin December 28, 2021 Leave a comment

Questions:

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?

Answers:

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.