How do you duplicate this feature in Java?
In C#, you could use the params
keyword to specify variable parameter lists for functions.
How do you do that in Java?
Or do you have to resort to multiple overloads?
C# code:
double Average(params double[] nums) {
var sum = 0.0;
foreach(var num in nums)
sum += num;
return sum / nums.Length;
}
Equivalent Java code:
double average(double... nums) {
double sum = 0.0;
for(double num : nums)
sum += num;
return sum / nums.length;
}
This feature is known as varargs. You can read more about it here.
The parameters to variadic functions ("varargs" in Java-speak) are exposed to the Java function body as an array. The example from the Wikipedia entry illustrates this perfectly:
public static void printSpaced(Object... objects) {
for (Object o : objects)
System.out.print(o + " ");
}
// Can be used to print:
printSpaced(1, 2, "three");
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