11

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.

Tim
  • 5,767
  • 9
  • 45
  • 60
knorv
  • 49,059
  • 74
  • 210
  • 294

2 Answers2

23

Convert your ArrayList into an Array of type object.

ClassName.foo("something", "something", arrayList.toArray());
helloworld922
  • 10,801
  • 5
  • 48
  • 85
  • Oh, it was that simple! I thought Object... != Object[]. Thanks! :-) – knorv Jan 15 '11 at 22:17
  • In general Object != Object[], but for varargs methods, the compiler converts a MyType... parameter into a MyType[] parameter, and wraps all arguments into an array at runtime which gets passed to the function. So in this case, you get to take advantage of the secret internal signature of the varargs method by explicitly passing in an array reference. – Dov Wasserman Jan 15 '11 at 22:57
-1

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.

EnabrenTane
  • 7,428
  • 2
  • 26
  • 44
  • I can only control the code calling the foo method, so changing the foo method is not an option. – knorv Jan 15 '11 at 22:05