Java泛型和Array的 [英] Java generics and Array's
本文介绍了Java泛型和Array的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码片段在我的单元测试中运行时有意义。我在标有'>>>>'的行上得到一个ClassCastException(对象不能转换为字符串)。这种类型的操作可以通用吗?
The following snippet makes sense yet when I run this against my unit test.. I get a ClassCastException (Object can't be cast to String) on the line marked with '>>>>'. Can this type of operation be done in a generic ?
public class ArrayUtils<E> {
public static <E> E[] appendToArray(E[] array, E item) {
E[] result = (E[])new Object[array.length+1];
for(int i=0; i < array.length; i++ ) {
result[i] = array[i];
}
result[result.length-1] = item;
return result;
}
}
@Test
public void testAppendToArray() {
String[] array = new String[1];
array[0] = "a";
assertSame("Array is not correct length.", 1, array.length );
>>>> String[] appendToArray = ArrayUtils.<String>appendToArray(array, "b");
assertSame("Array is not correct length.", 2, appendToArray.length );
}
推荐答案
你不应该创建你的数组使用新的Object []。您应该使用 Array.newInstance(Class clazz,int length)
来代替。
You should not create your array using new Object[]. You should use Array.newInstance(Class clazz, int length)
instead.
这篇关于Java泛型和Array的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文