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?
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");
You can use ...
. For example:
public void foo(int... args) {
for (int arg : args) {
// do something
}
}