数组扩容(3种解决方案)
方案1:
int[] a = {1, 2, 3, 4, 5};
// 创建新数组,长度为源数组的两倍
int[] b = new int[a.length * 2];
// 将旧数组内容复制到新数组
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
// 新数组内容赋值给源数组
a = b;
// 打印结果
System.out.println(Arrays.toString(a));
输出结果
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
方案2:
int[] a = {1, 2, 3, 4, 5};
// 第一个参数是拷贝的数组,第二个参数是扩容长度,且返回一个新数组
a = Arrays.copyOf(a, a.length * 2);
// 打印结果
System.out.println(Arrays.toString(a));
输出结果
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
方案3:
int[] a = {1, 2, 3, 4, 5};
// 定义新数组,长度为源数组的两倍
int[] b = new int[a.length * 2];
/**
* src 需要拷贝的源数组
* srcPos 源数组中的起始位置
* dest 目标数组
* destPos 目标数组中的起始位置
* length 要复制的数组元素数量
*/
System.arraycopy(a, 0, b, 0, a.length);
// 新数组内容赋值给原数组
a = b;
// 打印结果
System.out.println(Arrays.toString(a));
输出结果
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]