Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 512
knorv Avatar asked Jan 15 '11 21:01

knorv


People also ask

How do you duplicate an ArrayList?

The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object.

Can I pass array to Varargs Java?

Java static code analysis: Arrays should not be created for varargs parameters.


1 Answers

Convert your ArrayList into an Array of type object.

ClassName.foo("something", "something", arrayList.toArray());
like image 79
helloworld922 Avatar answered Oct 19 '22 01:10

helloworld922