Arrays类中的copyOf()方法允许动态的创建数组,可增大数组空间
int[] a=new int[100]; a=Arrays.copyOf(a, 2*a.length);//增大数组空间copyOf()方法有两种类型,一种是int型数组,另一种是泛型数组,可适用任意变量类型的数组 下面是其源代码
public static int[] copyOf(int[] original, int newLength) { int[] copy = new int[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }System提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制。
* @param src the source array. * @param srcPos starting position in the source array. * @param dest the destination array. * @param destPos starting position in the destination data. * @param length the number of array elements to be copied. * @exception IndexOutOfBoundsException if copying would cause * access of data outside array bounds. * @exception ArrayStoreException if an element in the <code>src</code> * array could not be stored into the <code>dest</code> array * because of a type mismatch. * @exception NullPointerException if either <code>src</code> or * <code>dest</code> is <code>null</code>. */ public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length); src:源数组; srcPos:源数组要复制的起始位置; dest:目的数组; destPos:目的数组放置的起始位置; length:复制的长度当是泛型数组时,会先实例化对应类型的copy数组,然后在调用原生函数System.arraycopy()方法增大数组空间
public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); } public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }也可以利用反射实现泛型数组扩展功能,java.lang.reflect包中的Array类允许动态地创建数组
public class TestArrayChangeSize { public static void main(String[] args) { int[] a=new int[2]; a[0]=0; a[1]=1; for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(); a=(int[]) ChangeSize(a, 5); a[2]=2; a[3]=3; a[4]=4; for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(); String[] b=new String[2]; b[0]="A"; b[1]="B"; for(int i=0;i<b.length;i++){ System.out.print(b[i]+" "); } System.out.println(); b=(String[]) ChangeSize(b, 5); b[2]="C"; b[3]="D"; b[4]="E"; for(int i=0;i<b.length;i++){ System.out.print(b[i]+" "); } System.out.println(); } public static Object ChangeSize(Object obj, int newlength){ Class c=obj.getClass(); if(!c.isArray()){ return null; } Class componenttype=c.getComponentType();//获取传进来的数组类型 int oldlength=Array.getLength(obj); Object newobj=Array.newInstance(componenttype, newlength);//主要是这句话,用来实例化对应类型的数组 System.arraycopy(obj, 0, newobj, 0, Math.min(oldlength, newlength)); return newobj; } }结果:int[]和String[]都增大空间了
0 1 0 1 2 3 4 A B A B C D E