Passing a List in as varargs

JavaAndroidListVariadic Functions

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxbakesxView Question on Stackoverflow
Solution 1 - JavaSLaksView Answer on Stackoverflow
Solution 2 - JavazellerView Answer on Stackoverflow