为了使数组的大小增加一倍,让我们首先创建一个数组-
int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
现在,获取上述数组的长度-
int len = arr.length;
将上述数组的大小加倍-
intnewArray[] = new int[len*2];
现在,newArray []的长度将是数组arr []的两倍。
public class Demo { public static void main (String args[]) { int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}; System.out.println("Length of initial array = " + arr.length); int len = arr.length; int newArray[] = new int[len*2]; System.arraycopy(arr, 0, newArray, 0, len); System.out.println("Length of new array = "+newArray.length); } }
输出结果
Length of initial array = 10 Length of new array = 20