Java Variable Function Parameters

How do you duplicate this function in Java?

In C #, you can use the params to specify lists of variable variables for functions.

How do you do this in Java?

Or do you have to resort to several overloads?

+4
source share
4 answers

C # code:

 double Average(params double[] nums) { var sum = 0.0; foreach(var num in nums) sum += num; return sum / nums.Length; } 

Java equivalent code:

 double average(double... nums) { double sum = 0.0; for(double num : nums) sum += num; return sum / nums.length; } 

This function is called varargs. You can learn more about this here .

+9
source

Parameters of variational functions (" varargs " in Java-talk) are exposed to the body of the Java function as an array. The Wikipedia entry example 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"); 
+3
source

You can use ... For instance:

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

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

0
source

Source: https://habr.com/ru/post/1305514/


All Articles