Java: Passing a list as argument to a vararg method

The parameter type String... is equivalent to String[] so just use the List.toArray(T[] arr) method to convert the list to an array. For example:

varargMethod(strList.toArray(new String[strList.size()]));

where strList is of type List<String> would correctly invoke the following method

void varargMethod(String... strs) {
    ...
}

strs.toArray(new String[0]) also works, but you would unnecessarily allocate a zero length array that is immediately thrown away.

Comments

Be the first to comment!