当前位置: 代码迷 >> J2SE >> 运用反射编扩展数组,运行结果总是出错
  详细解决方案

运用反射编扩展数组,运行结果总是出错

热度:87   发布时间:2016-04-24 12:24:07.0
使用反射编扩展数组,运行结果总是出错
今天在自学反射内容时, 编写了下面一个程序;用于扩展任意数组;无论我怎样修改结果总是
int[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
请各路高手在闲暇时帮忙分析一下,万分感谢
//
import java.lang.reflect.Array;

public class ArrayGrowTest {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4 };
a = (int[]) goodArrayGrow(a);
arrayPrint(a);
}

public static Object goodArrayGrow(Object o) {
Class cl = o.getClass();
if (!cl.isArray())
return null;
int length = Array.getLength(o);
int newLength = length * 11 / 10 + 10;
Class componentType = cl.getComponentType();
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(newArray, 0, o, 0, length);
return newArray;
}

public static void arrayPrint(Object o) {
Class cl = o.getClass();
if (!cl.isArray())
return;
Class componentType = cl.getComponentType();
int length = Array.getLength(o);
System.out.print(componentType.getName() + "[" + length + "] = {");
for (int i = 0; i < length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(Array.get(o, i));
}
System.out.println("}");
}
}


------解决方案--------------------
System.arraycopy(o, 0, newArray, 0, length);
------解决方案--------------------
探讨
System.arraycopy(o, 0, newArray, 0, length);
  相关解决方案