数组的扩容

方式一:

        创建一个新的比原来数组长度长的数组,将原数组中的元素依次复制到新数组中。

public class test {
    public static void main(String[] args) {
        int[] old=new int[]{10,20,30,40,50};
        
        int[] newArr=new int[old.length*2];
        //复制数组
        for (int i = 0; i < old.length; i++) {
            newArr[i]=old[i];
        }
        //遍历新数组
        for (int i : newArr) {
            System.out.println(i);
        }

        //将新地址赋值给原数组
        old=newArr;
}

方式二:

调用System.arraycopy(原数组,原数组起始,新数组,新数组起始,长度);

public class test {
    public static void main(String[] args) {
        int[] old=new int[]{10,20,30,40,50};
        
        int[] newArr=new int[old.length*2];
        //复制数组
        System.arraycopy(old,0,newArr,0,old.length);
        //遍历新数组
        for (int i : newArr) {
            System.out.println(i);
        }

        //将新地址赋值给原数组
        old=newArr;
}

方式三:

调用Arrays.copyOf(原数组, 新长度)。会返回带有原值的新数组。

public class test {
    public static void main(String[] args) {
        int[] old=new int[]{10,20,30,40,50};
        
        //复制数组
        int[] newArr = Arrays.copyOf(old, old.length * 2);
        //遍历数组
        for (int i : newArr) {
            System.out.println(i);
        }

        //将新地址赋值给原数组
        old=newArr;
}

注意:

  • 数组作为引用类型之一,其变量中存储的是数组的地址。

  • 完成元素复制后,需将新数组地址,赋值给原变量进行替换。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值