动态数组使用

动态数组

动态数组意义

为什么会有动态数组这个概念?相比于普通的数组,普通数组有很多的局限性,比如数组的长度是固定的,不能随意增加,只能根据固定的数字长度写入适当的元素。而动态数组就很好的解决了这个问题,动态数组能根据写入的元素个数增加相应的数组长度。

实现动态数组

数组扩容

数组一旦装满元素,可进行数组扩容操作,即新建一个更长的数组,并转移元素至新数组,并将引用指向新数组,完成数组的变更。

public class DynamicArray {
    int [] A;
    int index ;
    int length ;

    public DynamicArray(int n) {//创建对象时传入一个初始容量
        if(n<0){
            throw new IllegalArgumentException("非法数字,数字需大于0");
        }
        length = n;
        A = new int[length];
        index = 0;
    }

    public void add (int a){

        if(index == length){//扩容
            int oldLength = length;
            length = oldLength + (oldLength >> 1);
            int [] newA = new int[length];
            for(int i = 0 ; i < oldLength ; i++){//将原数组中的元素全部移动到新数组中
                newA [i] = A [i];
                System.out.println(newA[i]);
            }
            A = newA;// 用原本数组对象变量名存储新数组对象变量名中的引用地址

        }
        A [index] = a;
        index++;
    }
    public int get(int index){
        if(index>=0&&index < length){
            int a = A[index];
            return a;
        }
        throw new ArrayIndexOutOfBoundsException ("inde:"+index+" length:"+length);
    }

    public static void main(String[] args){


        DynamicArray B = new DynamicArray(10);
        for(int i = 0;i < 30; i++){
            B.add(6);
        }
        System.out.println(B.get(20));


    }

}

数组缩减

数组元素相对总容量来说过少(比如只使用了四分之一空间),可进行数组缩减操作,即新建一个更短的数组,并转移元素至新数组,完成数组的变更。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nothing8727

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值