<分区>
我有一个实用程序类:
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;
}
}
当我测试 concat
时,它崩溃了:
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);
}
}
带有消息
java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Integer[]
我想这与泛型有关。你能提供让它发挥作用的建议吗?另外,这个问题的背景会很好。
谢谢!