Alexey Romanov
Alexey Romanov

Reputation: 170745

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?

Upvotes: 4

Views: 1557

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198133

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.

Upvotes: 5

Thomas
Thomas

Reputation: 88707

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) );

Upvotes: 3

hmjd
hmjd

Reputation: 121971

A possibility would be to overload foo():

public void foo(Object... x) {}
public void foo(Object[] a, Object... x) {}

Upvotes: 1

Related Questions