Java 数组扩容(3种解决方案)

数组扩容(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]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值