Java中数组的扩容采用的是System.arraycopy()方法
- 一维数组扩容
public class Test {
public static void main (String[] args) {
expansionOne();
}
// 一维数组扩容
public static void expansionOne () {
// 定义一个源数组
int[] array = {1, 2, 3, 4};
// 定义一个目标数组
int[] arraycopy = new int[10];
// 原数组扩容到目标数组中
/*
参数1:源数组
参数2:从源数组的什么位置开始扩容到目标数组
参数3:目标数组
参数4:目标数组从什么位置开始接受扩容过来的源数组
参数5:为源数组需要扩容到目标数组的长度(length)
*/
System.arraycopy(array, 0, arraycopy, 0, 4);
// 对数组循环遍历得到其中的数据
for (int i = 0 ; i < arraycopy.length ; i ++) {
System.out.println(arraycopy[i]);
}
}
}
输入结果:1 2 3 4 0 0 0 0 0 0
- 二维数组扩容
public class Test {
public static void main (String[] args) {
expansionTwo();
}
// 二维数组扩容
public static void expansionTwo () {
// 定义一个源数组
String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}};
// 定义一个目标数组
String[][] arraycopy = new String[5][3];
// 原数组扩容到目标数组中
/*
参数1:源数组
参数2:从源数组的什么位置开始扩容到目标数组
参数3:目标数组
参数4:目标数组从什么位置开始接受扩容过来的源数组
参数5:为源数组需要扩容到目标数组的长度(length)
*/
System.arraycopy(array, 0, arraycopy, 0, 2);
// 对数组循环遍历得到其中的数据
for (int m = 0 ; m < arraycopy.length ; m ++) {
for (int n = 0 ; n < arraycopy[m].length ; n ++) {
System.out.print(arraycopy[m][n] + " ");
}
}
}
}
输出结果:a b c d e f null null null null null null null null null
- 数组为什么要扩容呢?因为数组不能像集合一样添加数据,当我们创建好一个固定长度的数组时,这时数组的长度就不可以改变了。所以当我们数组长度不够时,只能通过扩容,就是新建一个大数组,将小数组中的数据拷贝到大数组中,然后小数组这个对象就自动被垃圾回收期回收了。