I have a utility class:
public class ArrayUtils {
public static <T> T[] concat(T[]... arrays) {
if(arrays == null) {
return null;
}
int size = 0;
for(T[] array : arrays) {
size += array.length;
}
T[] concatenatedArray = (T[]) new Object[size];
int i = 0;
for(T[] array : arrays) {
for(T item : array) {
concatenatedArray[i++] = item;
}
}
return concatenatedArray;
}
}
When I test concat
, it crushes:
public class ArrayUtilsTest extends TestCase {
public void testConcat() throws Exception {
Integer[] first = new Integer[]{1,2,3};
Integer[] second = new Integer[]{4,5,6};
Integer[] concat = ArrayUtils.concat(first, second);
assertEquals(6, concat.length);
}
}
with message
java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Integer[]
I guess it has to do with generics. Could you provide suggestions on making it work? Also, background on the issue would be great.
Thanks!