ntalbs ntalbs - 5 months ago 10x
Java Question

Is varargs of array possible in Java?

I tried to implement a method to merge any number of arrays.

public static <T> T[] merge(T[]... arrs) {
int length = 0;
for (T[] arr : arrs) {
length += arr.length;

T[] merged = (T[]) new Object[length];
int destPos = 0;
for (T[] arr : arrs) {
System.arraycopy(arr, 0, merged, destPos, arr.length);
destPos += arr.length;
return merged;

It compiled, and looked no problem. Then I tested this method like this:

String[] a = {"a", "b", "c"};
String[] b = {"e", "f"};
String[] c = {"g", "h", "i"};

String[] m = merge(a,b,c);

Though this code successfully compiled, it throws an exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at ntalbs.test.ArrayMerge.main(ArrayMerge.java:25)

Code looks plausible and compiled successfully, but doesn't work and throws an exception at runtime. Could you explain why this code doesn't work? What am I missing?


Your problem is not because of varargs.

It's because of the line,

T[] merged = (T[]) new Object[length];

An Object array cannot be cast to a String array.


T[] merged = (T[])java.lang.reflect.Array.newInstance(
                            arrs[0].getClass().getComponentType(), length);


As pointed out by @JB, this will only work if you try to merge the same array types. If you want to merge different array types, then you have to find the super type common to all of the arrays and use that in place of arrs[0].getClass().