Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most readable way to add elements to Java vararg call

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?

like image 252
Alexey Romanov Avatar asked Jan 18 '23 12:01

Alexey Romanov


2 Answers

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.

like image 65
Louis Wasserman Avatar answered Jan 20 '23 01:01

Louis Wasserman


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) );
like image 26
Thomas Avatar answered Jan 20 '23 03:01

Thomas