您的位置:首页 > 编程语言 > Java开发

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

2012-11-20 16:04 543 查看
今天看了下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://orangleliu.blog.51cto.com/2554001/1064881
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: