I tried to implement a method to merge any number of arrays.
@SuppressWarnings("unchecked")
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?
T[] merged = (T[]) new Object[length];not the array varargs.new Object[]which cannot be cast to aString[]