Actually, because for compatibility reasons, the signature of a method, which is using varargs function(Object... args) is the equivalent of a method declared with an array function(Object[] args).
Therefore in order to pass and spread any collection to function which expects varargs, you need to transform it to the array:
import java.util.Arrays;
import java.util.stream.Stream;
public class MyClass {
static void printMany(String ...elements) {
Arrays.stream(elements).forEach(System.out::println);
}
public static void main(String[] args) {
printMany("one", "two", "three");
printMany(new String[]{"one", "two", "three"});
printMany(Stream.of("one", "two", "three").toArray(String[]::new));
printMany(Arrays.asList("foo", "bar", "baz").toArray(new String[3]));
}
}
All these calls of printMany will print:
one
two
three
It's not exactly the same as spread operator, but in most cases, it's good enough.
Answer from Krzysztof Atłasik on Stack OverflowActually, because for compatibility reasons, the signature of a method, which is using varargs function(Object... args) is the equivalent of a method declared with an array function(Object[] args).
Therefore in order to pass and spread any collection to function which expects varargs, you need to transform it to the array:
import java.util.Arrays;
import java.util.stream.Stream;
public class MyClass {
static void printMany(String ...elements) {
Arrays.stream(elements).forEach(System.out::println);
}
public static void main(String[] args) {
printMany("one", "two", "three");
printMany(new String[]{"one", "two", "three"});
printMany(Stream.of("one", "two", "three").toArray(String[]::new));
printMany(Arrays.asList("foo", "bar", "baz").toArray(new String[3]));
}
}
All these calls of printMany will print:
one
two
three
It's not exactly the same as spread operator, but in most cases, it's good enough.
In java there is concept of Variable Arguments, using which you can pass different numbers of arguments to same function.
I am taking your code as an example :
public class Foo {
public int doSomething (int ...a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
}
Now you can call this function as :
doSomething (args)
For more information you can visit below link : http://www.geeksforgeeks.org/variable-arguments-varargs-in-java/
Recently found out about it when trying to learn about coroutines. Was curious about how often people use it (just used it now for the first time).