views:

202

answers:

4

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?

+8  A: 

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.

missingfaktor
+2  A: 

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");
Will
+2  A: 

You can use .... For example:

public void foo(int... args) {
  for (int arg : args) {
    // do something
  }
}
koppernickus
A: 

In Java you can use varargs. But this works only for 1.5 or newer versions.

codaddict