Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java variable function parameters

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?

like image 455
Olaseni Avatar asked Dec 09 '22 16:12

Olaseni


2 Answers

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.

like image 127
missingfaktor Avatar answered Dec 15 '22 00:12

missingfaktor


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");
like image 22
Will Avatar answered Dec 14 '22 22:12

Will