问题
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
回答1:
Just pass things.toArray(new Thing[things.size()]).
回答2:
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.
来源:https://stackoverflow.com/questions/12220324/passing-a-list-in-as-varargs