Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a List to variable argument parameter java

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?

like image 577
java_geek Avatar asked May 25 '13 10:05

java_geek


People also ask

How do you pass a list to a variable argument in Java?

Use List. toArray(T[] arr) : yourVarargMethod(yourList.

How do you pass a list to a string in Java?

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.

What is var ARG method in Java?

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 }


2 Answers

String... equals a String[] So just convert your list to a String[] and you should be fine.

like image 165
FloF Avatar answered Oct 07 '22 05:10

FloF


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.

like image 20
Alpesh Gediya Avatar answered Oct 07 '22 05:10

Alpesh Gediya