Java数组扩容的三种方式

实现数组扩容的方式

for循环
System.arraycopy
Arrays.copyOf

方法一 for循环

/**
     * 方法一:使用for循环
     */
    public static int[] enlarge1(){
        int[] a = {1,2,3,4,5};
        int[] b = new int[10];
        // 将数组 a 的元素赋给 b
        for(int i = 0; i < a.length; i++){
            b[i] = a[i];
        }
        return b; //1 2 3 4 5 0 0 0 0 0
    }

方法二:使用System.arraycopy

System.arrayCopy的源代码声明 :

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
代码解释:
  Object src : 源数组
   int srcPos : 源数组的起始位置
  Object dest : 目标数组
  int destPos : 目标数组的起始位置
  int length  : 复制的长度
/**
     * 方法二:使用System.arraycopy
     */
    public static int[] enlarge2(){
        int[] a = {1,2,3,4,5};
        int[] b = new int[10];
        System.arraycopy(a,0,b,0,a.length);
        return b; //1 2 3 4 5 0 0 0 0 0
    }

方法三:使用Arrays.copyOf

//original - 要复制的数组
//newLength - 要返回的副本的长度
public static <T> T[] copyOf(T[] original,
                             int newLength)

 /**
     * 方法三:使用Arrays.copyOf
     */
    public static int[] enlarge3(){
        int[] a = {1,2,3,4,5};
        int[] b = Arrays.copyOf(a,10);
        return b; //1 2 3 4 5 0 0 0 0 0
    }

其实Arrays.copyOf 的底层还是调用 System.arraycopy

在这里插入图片描述
两者的区别在于:
Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。
所以,Arrays.copyOf()方法传回的数组是新的数组对象,改变传回数组中的元素值,不会影响原来的数组。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值