I have a method which takes a variable length string (String...) as parameter. I have a List<String>
with me. How can I pass this to the method as argument?
Use List. toArray(T[] arr) : yourVarargMethod(yourList.
Using List. We can use the toArray(T[]) method to copy the list into a newly allocated string array. We can either pass a string array as an argument to the toArray() method or pass an empty string type array. If an empty array is passed, JVM will allocate memory for the string array.
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }
String...
equals a String[]
So just convert your list
to a String[]
and you should be fine.
String ... and String[] are identical If you convert your list to array.
using
Foo[] array = list.toArray(new Foo[list.size()]);
or
Foo[] array = new Foo[list.size()]; list.toArray(array);
then use that array as String ...
argument to function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With