[Java的] 改变Java数组元素的数量 – 调整中的Java数组的长度
在Java中,以改变所述阵列的大小,我们将原始数组复制到另一个阵列具有所需尺寸.
public class ReSizeArray{ public int[] reSize(int[] a, int size){ int[] temp = new int [size]; System.arraycopy(a, 0, temp, 0, (a.length < size) ? a.length : size); return temp; } public void outPut(int[] a){ for (int i=0; i<a.length; i++) System.out.print(a[i]+" "); } public static void main(String [] agrs){ ReSizeArray ns = new ReSizeArray(); int[] a = new int[5]; for (int i=0; i<a.length; i++) a[i] = i; System.out.println("nBefor change length of a = " + a.length); ns.outPut(a); a = ns.reSize(a, 20); for (int i=5; i<a.length; i++) a[i] = i; System.out.println("nAfter change length of a = " + a.length); ns.outPut(a); } }
最新评论