I've got an arrayList filled with elements. I would like to pass the elements of that array list as arguments to a variadic function.
My function
public SequenceEntityModifier(final IEntityModifier... pEntityModifiers)
My ArrayList
ArrayList<IEntityModifier> arr = new ArrayList<IEntityModifier>();
arr.add(new MoveXModifier(1, 50, 120));
arr.add(new MoveXModifier(1, 120, 50));
I'd like to pass it to the function as if I would pass them individually.
new SequenceEntityModifier( /* elements of arr here */ );
Is something like this possible?
Thanks in advance.
Just do:
This copies the
ArrayList
to the given array and returns it. All vararg functions can also take arrays for the argument, so for:All the legal calls are:
One caveat:
Vararg calls involving primitive arrays don't work as you would expect. For example:
One might expect this to print
1
,2
, and3
, on separate lines. Instead, it prints something like[I@1242719c
(the defaulttoString
result for anint[]
). This is because it's ultimately creating anObject[]
with one element, which is ourint[]
, e.g.:Same goes for
double[]
,char[]
, and other primitive array types. Note that this can be fixed simply by changing the type ofintArray
toInteger[]
. This may not be simple if you're working with an existing array since you cannot cast anint[]
directly to anInteger[]
(see this question, I'm particularly fond of theArrayUtils.toObject
methods from Apache Commons Lang).The construct
IEntityModifier...
is syntactic sugar forIEntityModifier[]
See the appropriate JLS section (8.4.1 Formal Parameters)
I always create an overload that takes
Iterable< ? extends IEntityModifier >
, and make the variadic version forward to this one usingArrays.asList()
, which is cheap.