/**
* 使用一个新大小重设数组,并拷贝旧数组的内容到新数组
* @param oldArray 旧数组被重设
* @param newSize 新数组大小
* @return 返回带同样内容的新数组
*/
private static Object resizeArray (Object oldArray, int newSize){
int oldSize = java.lang.reflect.Array.getLength(oldArray);
Class elementType = oldArray.getClass().getComponentType();
Object newArray = java.lang.reflect.Array.newInstance(
elementType,newSize);
int preserveLength = Math.min(oldSize,newSize);
if (preserveLength > 0)
System.arraycopy (oldArray,0,newArray,0,preserveLength);
return newArray;
}
// resizeArray()测试用例
public static void main (String[] args) {
int[] a = {1,2,3};
a = (int[])resizeArray(a,5);
a[3] = 4;
a[4] = 5;
for (int i=0; i<a.length; i++)
System.out.println (a[i]); }
那二维数组如何重设大小呢? 很简单,就是处理数组的数组呀!
要想重设二维数组,resizeArray方法必须处理外部数组和所有嵌套数组,如下例:
int a[][] = new int[2][3];
//...
a = (int[][])resizeArray(a,20);
// 新数组是[20][3]
for (int i=0; i<a.length; i++) {
if (a[i] == null)
a[i] = new int[30];
else a[i] = (int[])resizeArray(a[i],30);
}
// 新数组是[20][30]
http://www.blogjava.net/mlh123caoer/archive/2007/09/19/146367.html