3

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?

1
  • 1
    String... is equivalent to String[] Commented Jan 5, 2012 at 11:18

5 Answers 5

10

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()]));
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

String... is the same as String[].

You want to call something like:

String[] listArr = list.toArray( new String[ list.size() ] );
doSomething( listArr );

Comments

1

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).

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.