Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Overloading and Arguments with Generics in Java

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?

like image 660
mostar Avatar asked Sep 04 '12 06:09

mostar


People also ask

How do you overload a generic method in Java?

A generic method can also be overloaded by nongeneric methods. When the compiler encounters a method call, it searches for the method declaration that best matches the method name and the argument types specified in the call—an error occurs if two or more overloaded methods both could be considered best ...

Can we overload generic methods?

Answer: Yes, we can overload a generic methods in C# as we overload a normal method in a class. Q- If we overload generic method in C# with specific data type which one would get called?

Which types can be used as arguments of generics?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).


1 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.

like image 101
Thomas Jungblut Avatar answered Sep 21 '22 00:09

Thomas Jungblut