Reputation: 1721
Recently I came across an API and it was using some Parameter
void doSomething(final String... olah) {
}
I never have seen something like that.
I have a List<String>
now and I want to call that function with my list of string. How can I achieve that?
Upvotes: 3
Views: 952
Reputation: 53687
See the following to convert List of String to String Array
List<String> listOfString = new ArrayList<String>();
listOfString.add("sunil");
listOfString.add("sahoo");
String[] strResult=new String[listOfString.size()];
strResult = listOfString.toArray(strResult);
Upvotes: 1
Reputation: 59694
String...
is nothing but String[]
. So just loop over list and create an array of String and pass that array or more easy way to use .toArray(new String[collection.size()])
method of Collection class.
Upvotes: 3
Reputation: 24319
Use .toArray(new String[0])
. The toArray() method will turn your list of strings (java.util.List<String>
) into an array of String
objects.
The '...' syntax is a mechanism to allow a variable number of parameters. You can pass either something like doSomething("abc", "def", "ghi")
or doSomething("abc")
or doSomething(new String[] { "abc", "def", "ghi" })
. The function will see them all as arrays (respectively as length 3, 1 and 3).
Upvotes: 1
Reputation: 62603
Welcome to modern Java. That syntax is called varargs
in Java.
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
You can think of it like
void doSomething(final String[] olaf) {
}
The only difference is that as the name suggests, it is Variable Length Arguments. You can invoke it with 0
to any number or arguments. Thus, doSomething("foo")
, doSomething("foo", "bar")
, doSomething("foo", "bar", "baz")
are all supported.
In order to invoke this method with a List
argument though, you'll have to first convert the list into a String[]
.
Something like this will do:
List<String> myList; // Hope you're acquainted with generics?
doSomething(myList.toArray(new String[myList.size()]));
Upvotes: 10
Reputation: 3053
String... is the same as String[].
You want to call something like:
String[] listArr = list.toArray( new String[ list.size() ] );
doSomething( listArr );
Upvotes: 2