Reputation: 75
Can you help me? What does int[]... arrays mean in Java? Example:
public static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
Upvotes: 2
Views: 15497
Reputation: 95958
This means that you can pass the method any number of int[]
objects:
concat(new int[]{1,2});
concat(new int[]{1,2}, new int[]{3,4,5});
concat(new int[]{1}, new int[]{3,4,5,6}, new int[]{1,1,1,1,1,1,1});
Why this is useful? It's clear why :)
Upvotes: 1
Reputation: 121998
That is called varargs.. notation
,
So that you can pass individual int[]
objects to that method,, without worrying of no.of arguments.
When you write
public static int[] concat(int[]... arrays) {
Now you can use that method like
Classname.concat(array1,array2,array3) //example1
Classname.concat(array1,array2) //example2
Classname.concat(array1,array2,array3,array4) //example3
A clear benefit is you need not to prepare an array to pass a method. You can pass values of that array directly.
Upvotes: 4
Reputation: 6965
The ellipsis (...) identifies a variable number of arguments, and is demonstrated in the following summation method.
public static int[] concat(int[]... arrays)
Use method
concat(val1, val2, val3);
concat(val1, val2, val3, val3);
Upvotes: 0
Reputation: 437
For example you have a method:
void functionName (Object objects...)
{
Object object1=objects[0];
Object object2=objects[1];
Object object3=objects[2];
}
You can use your method as:
Object object1,object2,object3;
functionName(object1,object2,object3);
Upvotes: 0
Reputation: 2672
varargs ("...") notation basically informs that the arguments may be passed as a sequence of arguments (here - ints) or as an array of arguments. In your case, as your argument is of type "array of int", it means arguments may be passed as a sequence of arrays or as an array of arrays of int (note that array of arrays is quite equivalent to multidimensional array in Java).
Upvotes: 0
Reputation: 8695
This means, that you can pass zero, one or more arrays of int (int[]
) to your method. Consider following example
public void method(String ... strings)
can be called as
method()
method("s")
method("s", "d")
So your method can be called as
concat()
concat(new int[0])
concat(new int[0], new int[0])
Upvotes: 1
Reputation: 5769
It means that the concat
function can receive zero or more arrays of integers (int[]
). That's why you can loop over the arrays
argument, accessing one of the arrays contained in each iteration - if any. This is called variable arguments (or varargs
).
Check this other question for more info.
Upvotes: 1
Reputation: 18445
The ...
is the most important part, it means you can have an unlimited amount of integers passed in and it is just accessed via the array, so you could call it as:
concat(1,2,3,4,5)
or concat(1)
Most languages have this sort of feature, some call it var args others call it params.
Upvotes: 0