java中数组扩容的三种方式

java中数组扩容的三种方式

/**
 * 数组扩容
 */
public class ArrayKR {

    public static void main(String[] args) {
        test01();
        test02();
        test03();
    }

    /**
     * 方法一:
     * 1.新建一个长度是原来数组两倍的数组
     * 2.通过for循环将旧数组中的元素取出并拷贝到新数组中
     */
    public static void test01(){
        // 初始化数组
        int[] a={33,55,666,78};
        // 新建一个数组长度为原来的两倍
        int[] b=new int[a.length*2];
        // 将旧数组中的数据赋值给新数组
        for(int i=0;i<a.length;i++){
            b[i]=a[i];
        }
        System.out.println("test01原数组:" + Arrays.toString(a));
        System.out.println("test01扩容后的数组:" + Arrays.toString(b));

    }

    /**
     *方法二:使用Arrays.copyOf(array,to_index)
     */
    public static void test02(){
        /**
         * Arrays.copyOf(array,to_index): 返回一个新的数组 可以指定新数组的长度
         * array :原数组
         * to_index:指定的数组长度
         *
         * 源码:
         * public static int[] copyOf(int[] original, int newLength) {
         *         int[] copy = new int[newLength];
         *         System.arraycopy(original, 0, copy, 0,
         *                          Math.min(original.length, newLength));
         *         return copy;
         *     }
         * 从上面的源码中可以看出Arrays.copyOf(array,to_index) 底层是调用了System.arraycopy()方法
         * 而System.arraycopy()方法本质上是一个数组拷贝的方法 将源数组中的元素按指定的复制长度拷贝到目的数组中
         *
         * public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
         * src:源数组
         * srcPos:源数组要复制的起始位置
         * dest:目的数组
         * destPos: 目的数组放置的起始位置
         * length:复制长度(复制元素的个数)
         */
        int[] a={333,555,666,888};
        int[] b= Arrays.copyOf(a,a.length*2);
        System.out.println("test02原数组:" + Arrays.toString(a));
        System.out.println("test02扩容后的数组:" + Arrays.toString(b));
    }

    /**
     * 方法三:使用System.arraycopy()方法
     */
    public static void test03(){
        // 初始化数组
        int[] a={12,23,45,56,67};
        // 创建新数组,长度是源数组的两倍
        int[] b= new int[a.length*2];

        // 将原数组中的元素拷贝到新数组中
        System.arraycopy(a,0,b,0,a.length);

        System.out.println("test03原数组:" + Arrays.toString(a));
        System.out.println("test03扩容后的数组:" + Arrays.toString(b));
    }

    /**
     * 小结:从上面三个方法中,可以看出数组扩容的思路是:
     * 1,先创建一个指定长度的新数组
     * 2. 将源数组中的元素拷贝到新数组中
     *
     *
     * 方法二和方法三实际上都是通过调用System.arraycopy()方法来实现数组的拷贝功能的
     * 方法三是直接调用System.arraycopy()方法,相对来说效率应该会更高一点
     *
     */
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值