开发者

How do I pass an ArrayList to a method expecting a vararg (Object...)? [duplicate]

This question already has answers here: How to pass an ArrayList to a varargs method parameter? (5 answers) Closed 7 years ago.

Assume a method with the following signature:

public static void foo(String arg1, String args2, Object... moreArgs);

When running ...

ClassName.foo("something", "something", "first", "second", "third");

... I'll get moreArgs[0] == "first", moreArgs[1] == "second" and moreArgs[2] == "third".

But assume that I have the parameters stored in an ArrayList<Stri开发者_Go百科ng> called arrayList which contains "first", "second" and "third".

I want to call foo so that moreArgs[0] == "first", moreArgs[1] == "second" and moreArgs[2] == "third" using the arrayList as a parameter.

My naïve attempt was ...

ClassName.foo("something", "something", arrayList);

... but that will give me moreArgs[0] == arrayList which is not what I wanted.

What is the correct way to pass arrayList to the foo method above so that moreArgs[0] == "first", moreArgs[1] == "second" and moreArgs[2] == "third"?

Please note that the number of arguments in arrayList happens to be three in this specific case, but the solution I'm looking for should obviously be general and work for any number of arguments in arrayList.


Convert your ArrayList into an Array of type object.

ClassName.foo("something", "something", arrayList.toArray());


You pass it just how you expect. However there is only one thing, and it is the reference to the ArrayList.

You then have to shift your stuff off the array list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜