Passing a List in as varargs
JavaAndroidListVariadic FunctionsJava Problem Overview
I have a List<Thing>
and I would like to pass it to a method declared doIt(final Thing... things)
. Is there a way to do that?
The code looks something like this:
public doIt(final Thing... things)
{
// things get done here
}
List<Thing> things = /* initialized with all my things */;
doIt(things);
That code obviously doesn't work because doIt()
takes Thing
not List<Thing>
.
Is there a way to pass in a List as the varargs?
This is in an Android App, but I don't see why the solution will not apply to anything Java
Java Solutions
Solution 1 - Java
Just pass things.toArray(new Thing[things.size()])
.
Solution 2 - Java
The variadic argument is internally interpreted as an array. So you should convert it into an array beforehands. Also in your doIt
method you should access things-s elements with array indexing.