I have a java program with a method that will consistently receive a different number of int
values. What is the best way to send it the ints
?
Asked
Active
Viewed 473 times
3

Andrew Tobilko
- 48,120
- 14
- 91
- 142

localplutonium
- 260
- 3
- 13
-
1Have you tried anything? just call the method with arguments... methodName( 1,2,3,4,5,6,7,8 ) – billjamesdev Apr 22 '16 at 05:16
-
i want a dynamic number of arguments – localplutonium Apr 22 '16 at 05:17
-
You say you HAVE a method that takes a dynamic length argument set... and ask how you call it. Dynamic arguments are so you can call it with any number of arguments, so one time you can call it with 1,2,3,4 and another time you can call it with 3,5,2,1,43,5,3,32. – billjamesdev Apr 22 '16 at 05:18
2 Answers
3
A construct called varargs (or an arbitrary number of arguments) helps you.
method(int... ints) { ... }
Then, varargs will be turned into int[]
by the compiler.
OK, how to call those methods?
method(1, 2, 3);
method(new int[]{1, 2, 3});
About the question in the comments:
method(Arrays.stream(yourStringArray).mapToInt(Integer::parseInt).toArray());
You may convert String[]
to int[]
firstly, and then pass the result to the method
.

Andrew Tobilko
- 48,120
- 14
- 91
- 142
-
would you consider this method better than sending it an array? i originally have a string array that contains the ints , which are the ints im sending to the method. – localplutonium Apr 22 '16 at 05:16
-
Using varargs is perfect because you can pass it an array OR many parameters with commas. It's your choice. – 4castle Apr 22 '16 at 05:18
-
`Arrays.stream(s).mapToInt(Integer::parseInt).toArray()` and pass `int[]` – Andrew Tobilko Apr 22 '16 at 05:19
1
Something like below you can do, making use of dot notation for method declaration with multiple arguments
public TestClass
{
public void process(int... variables)
{
// process your variables,
// Iterate through variables
}
}
Plus refer this, Java multiple arguments dot notation - Varargs

Community
- 1
- 1

Ankur Singhal
- 26,012
- 16
- 82
- 116