java中数组拷贝

正常学习的时候你是怎么拷贝或者复制数组的?

for循环挨个个赋值?java中提供了数组拷贝的方法,如下:

1.使用系统提供的类System.arraycopy

 
System.arraycopy(elements,0,data,0,elements.length);

public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

src:源数组;
srcPos:源数组要复制的起始位置;
dest:目的数组;
destPos:目的数组放置的起始位置;
length:复制的长度。
注意:src and dest都必须是同类型或者可以进行转换类型的数组.

 

2.使用Arrays提供的方法Arrays.copyOf()

使用方法如下

int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOf(arr1, 5);
int[] arr3 = Arrays.copyOf(arr1, 10);
for(int i = 0; i < arr2.length; i++) {
    System.out.print(arr2[i] + " ");
}
System.out.println();
for(int i = 0; i < arr3.length; i++) {
    System.out.print(arr3[i] + " ");
}

下面是源码Arrays.copyOf():我门来看一下是如何实现的

本质上还是调用了System.arraycopy()方法,

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()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值