[java]数组复制小结 for 、clone、 System.arraycopy

今天看了下ArrayList的源码,其中许多方法要用到数组的复制,而且全部使用的是System.arraycopy方法

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


参数:
src - 源数组。
srcPos - 源数组中的起始位置。
dest - 目标数组。
destPos - 目标数据中的起始位置。
length - 要复制的数组元素的数量。

从源码中看出它是一个本地方法。

由此对java中数组的复制3种方法做小结如下:

1.使用FOR循环,将数组的每个元素复制或者复制指定元素,效率差一点
2.使用clone方法,得到数组的值,而不是引用,不能复制指定元素,灵活性又不太好
3.使用System.arraycopy(src, srcPos, dest, destPos, length)方法,可以灵活使用,由于是本地方法,应当效率很高

小案例如下:

import java.util.*;
public class Test3 {
	public static void main(String[] args) {
		//1 使用System.arraycopy方法
		int[] fun1 ={0,1,2,3,4,5,6};
		System.arraycopy(fun1,0,fun1,3,3);
		for(int i=0;i<fun1.length;i++){
			System.out.print(fun1[i]+" ");
		}
		System.out.println("");
		//2 使用for循环的方法
		int[] fun2={0,1,2,3,4,5,6};
		int[] fun3=new int[7];
		for(int i=0;i<fun2.length;i++){
			fun3[i]=fun2[i];
		}
		for(int j=0;j<fun3.length;j++){
			System.out.print(fun3[j]+" ");
		}
		System.out.println("");
		//3 使用clone方法
		int[] fun4={0,1,2,3,4,5,6};
		int[] fun5=new int[7];
		fun5=fun4.clone();
		for(int i=0;i<fun5.length;i++){
			System.out.print(fun5[i]+" ");
		}				
	}
}

输出结果:
0 1 2 0 1 2 6 
0 1 2 3 4 5 6 
0 1 2 3 4 5 6 

System.arraycopy方法对于数组变化后重组新的数组很方面,clone和for循环就要取出来然后做判断了,比较麻烦。

部分引用自:http://qinheng053.blog.163.com/blog/static/873451120123921645688/

本文出自 orangleliu笔记本 博客,请务必保留此出处http://blog.csdn.net/orangleliu/article/details/38309431

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值