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?

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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");

Comments

2

You can use .... For example:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.