Java 程序来扩展一个整数数组的大小
我们首先创建一个整数数组 −
Integer[] arr = new Integer[] { 50, 100, 150, 200, 400, 500, 800, 1000};
现在,创建一个具有扩展大小的新数组 −
Integer[] new_size = new Integer[15];
添加扩展大小的元素 −
new_size[8] = 2000; new_size[9] = 3000; new_size[10] = 4000; new_size[11] = 5000; new_size[12] = 6000; new_size[13] = 9000; new_size[14] = 10000;
现在,复制数组,并使用扩展的大小形成最终数组 −
System.arraycopy(arr, 0, new_size, 0, arr.length);
例子
public class Demo { public static void main(String[] args) { Integer[] arr = new Integer[] { 50, 100, 150, 200, 400, 500, 800, 1000}; System.out.println("All the elements before extending the array..."); for (Integer i:arr) System.out.println(i); Integer[] new_size = new Integer[15]; new_size[8] = 2000; new_size[9] = 3000; new_size[10] = 4000; new_size[11] = 5000; new_size[12] = 6000; new_size[13] = 9000; new_size[14] = 10000; System.arraycopy(arr, 0, new_size, 0, arr.length); System.out.println("All the elements after extending the array..."); for (Integer i: new_size) System.out.println(i); } }
输出
All the elements before extending the array... 50 100 150 200 400 500 800 1000 All the elements after extending the array... 50 100 150 200 400 500 800 1000 2000 3000 4000 5000 6000 9000 10000
广告