Passing a combination of T and T [] to Java varargs method
Suppose you have Java method
void foobar(int id, String ... args)
and want to pass both String arrays and Strings to the method. Like this
String arr1[]={"adas", "adasda"};
String arr2[]={"adas", "adasda"};
foobar(0, "adsa", "asdas");
foobar(1, arr1);
foobar(2, arr1, arr2);
foobar(3, arr1, "asdas", arr2);
Python has a "*" for this. Some way is better than this rather ugly helper method:
static String[] concat(Object... args) {
List<String> result = new ArrayList<String>();
for (Object arg : args) {
if (arg instanceof String) {
String s = (String) arg;
result.add(s);
} else if (arg.getClass().isArray() && arg.getClass().getComponentType().equals(String.class)) {
String arr[] = (String[]) arg;
for (String s : arr) {
result.add(s);
}
} else {
throw new RuntimeException();
}
}
return result.toArray(new String[result.size()]);
}
What allow
foobar(4, concat(arr1, "asdas", arr2));
+2
a source to share
1 answer
Java doesn't have built-in syntactic sugar, but your helper method could be much nicer:
private static String[] concat(Object... stringOrArrays) {
List<String> result = new ArrayList<String>();
for (Object stringOrArray : stringOrArrays) {
if (stringOrArray instanceof String) {
result.add((String) stringOrArray);
} else if (stringOrArray instanceof String[]) {
Collections.addAll(result, (String[]) stringOrArray);
} else if (stringOrArray == null) {
results.add(null)
} else {
throw new RuntimeException(stringOrArray + " not a String or String[]");
}
}
return result.toArray(new String[0]);
}
I could come up with one liner (to avoid the method), but I don't recommend:
foobar(1, new ArrayList<String>() {{
addAll(Arrays.asList(arr1));
addAll(Arrays.asList(arr2));
add(arr3);
}}.toArray(new String[0]));
The only advantage one liner has is type safety.
+3
a source to share