今天在自学反射内容时, 编写了下面一个程序;用于扩展任意数组;无论我怎样修改结果总是
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("}");
}
}

解决方案 »

  1.   

    System.arraycopy(o, 0, newArray, 0, length);
      

  2.   

    +1
    void java.lang.System.arraycopy(Object array1, int start1, Object array2, int start2, int length)
    Copies the contents of array1 starting at offset start1 into array2 starting at offset start2 for length elements. 
    复制数组array1(开始复制的起始位置为start1)长度为length到数组array2(放置的起始位置为start2)中Parameters:
    array1 the array to copy out of
    start1 the starting index in array1
    array2 the array to copy into
    start2 the starting index in array2
    length the number of elements in the array to copy