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.
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.
Java static code analysis: Arrays should not be created for varargs parameters.
Convert your ArrayList into an Array of type object.
ClassName.foo("something", "something", arrayList.toArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With