If I have a method public void foo(Object... x)
, I can call it in this way:
Object[] bar = ...;
foo(bar);
However, this doesn't work:
Object baz = ...;
Object[] bar = ...;
foo(baz, bar);
Obviously, it can be done by creating an array with size 1 greater than bar
and copying baz
and the contents of bar
there. But is there some more readable shortcut?
Guava's ObjectArrays
class provides methods to concatenate a single object to the beginning or end of an array, largely for this purpose. There's no way to get around the linear overhead, but it's already built and tested for you.
Unfortunately, there's not out-of-the-box way to make that more readable.
However, you could create a helper method that would take an array and a vargs parameter and returns the array with the varargs appended.
Something like this:
public T[] append(T[] originalArray, T... additionalElements) { ... }
foo( append( bar, baz) );
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