java语言复制数组的四种方法:

1.System.arraycopy

2.使用clone 方法

3.Arrays.copyOf

4. for循环逐一复制

且执行效率:System.arraycopy > clone > Arrays.copyOf > for循环

1.System.arraycopy

jdk 1.6源码

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

举个列子:

  1. public class Main{  
  2.     public static void main(String[] args) { 
  3.          int[] a1={1,2,3,4,5,6};  
  4.          int[] a2={11,12,13,14,15,16}; 
  5.          System.arraycopy(a1, 2, a2, 3, 2);  
  6.          System.out.print("copy后结果:");  
  7.          for(int i=0;i<a2.length;i++){  
  8.              System.out.print(a2[i]+" ");      
  9.          }  
  10.     }  
  11. }  

2.使用clone 方法

Object.clone
从源码来看同样也是native方法,所以也是底层的C语言实现的,但返回为Object类型,所以赋值时将发生强转,所以效率不如1
 
protected native Object clone() throws CloneNotSupportedException;

3.Arrays.copyOf 

jdk1.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;
}

4、for循环

代码灵活,但效率低

posted on 2018-03-06 18:48  i-cff  阅读(291)  评论(0)    收藏  举报