How to add arguments to varargs?
java, variadic-functions
Solution
You can write a method like this:
public static Object[] merge(Object o, Object... arr) {
Object[] newArray = new Object[arr.length + 1];
newArray[0] = o;
System.arraycopy(arr, 0, newArray, 1, arr.length);
return newArray;
}
and, subsequently:
m2(merge("added", objs));
Problem
Suppose I have methods ``` void m1(Object... objs) { m2("added", objs); } ``` and ``` void m2(Object... objs) { for (Object o : objs) { // do something with Object o } } ``` If I call `m1("a", "b")`, I'd like `m2` to see an array of 3 Objects (Strings "added", "a" and "b"). However, instead `m2` sees just 2 objects: String "added" and an `Object[]` array, which internally contains Strings "a" and "b". How can I get the desired behavior, that is, I simply add elements to the varargs before forwarding them to another method?