Since Java 1.5, there is now the possibilty of using variable numbers of arguements (var args) in a single method:
public int addAll(int... myData){ int d = 0; for (int i : myData){ d += i; } return d; } //calling this method: int sum = addAll(1, 2, 3); //sum would equal 6.
The variable myData in the previous code is treated as an array of ints: int[]{ 1, 2, 3} and it could be also accessed like this:
public int addAll(int... myData){ int d = 0; for (int i = 0; i < myData.length; ++i){ d += myData[i]; } return d; } //calling this method: int sum = addAll(1, 2, 3); //sum would equal 6.
Note that if you use varargs, there is one restriction: It must be the last declared parameter in a method. Hence, you can have a method like this:
public void greetAll(int val, MyClass var, String... names){}
*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*