Java中动态修改数组(Array)的大小

上大王 分享于 20小时前 5107阅 0人收藏此代码, 我要收藏

Java中动态修改数组(Array)的大小,Java数组大小需要预先指定,下面的代码演示了如何在运行时修改数组的大小

/**
* Reallocates an array with a new size, and copies the contents
* of the old array to the new array.
* @param oldArray  the old array, to be reallocated.
* @param newSize   the new array size.
* @return          A new array with the same contents.
*/
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; 
}
 
// Test routine for resizeArray().
// http://www.sharejs.com
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]); 
}
//该代码片段来自于: http://www.sharejs.com/codes/java/8847

标签:
  • array
  • 数组大小
  • 动态数组