java中主要有四种复制数组的方法:
(1)System.arraycopy()
public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length);(2)for循环逐一复制
(3)Object中的clone();
(4)Arrays.copyof();从源代码可以看出仍然是调用arraycopy()方法
1
2
3
4
5
6
|
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;
}
|
然后是四种方法的运行时间测试结果,效率一次下降
public class copyArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] s1 = {"苹果","橘子","香蕉","哈密瓜","葡萄","火龙果","樱桃","梨子"};
String[] s2 = new String[8];
long time0=System.currentTimeMillis();
for(int j=0;j<10000000;j++){
System.arraycopy(s1, 0, s2, 0, s1.length);
}
long time1=System.currentTimeMillis();
System.out.println(time1-time0);
long time2=System.currentTimeMillis();
for(int j=0;j<10000000;j++){
for(int i=0;i<s1.length;i++){
s2[i]=s1[i];
}
}
long time3=System.currentTimeMillis();
System.out.println(time3-time2);
long time4=System.currentTimeMillis();
for(int j=0;j<10000000;j++){
s2=s1.clone();
}
long time5=System.currentTimeMillis();
System.out.println(time5-time4);
long time6=System.currentTimeMillis();
for(int j=0;j<10000000;j++){
s2=Arrays.copyOf(s1, s1.length);
}
long time7=System.currentTimeMillis();
System.out.println(time7-time6);
}
}
运行结果如下:
System.arraycopy:162ms
for循环:282ms
clone():1364ms
Arrays.copyOf():2066ms
总结:执行效率从最好到最差:System.arraycopy > for循环 > clone() > Arrays.copyOf()