Passing a List in as varargs [duplicate]

走远了吗. 提交于 2019-12-18 10:46:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!