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?
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 ...
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?
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With