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);
举个列子:
- public class Main{
- public static void main(String[] args) {
- int[] a1={1,2,3,4,5,6};
- int[] a2={11,12,13,14,15,16};
- System.arraycopy(a1, 2, a2, 3, 2);
- System.out.print("copy后结果:");
- for(int i=0;i<a2.length;i++){
- System.out.print(a2[i]+" ");
- }
- }
- }
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循环
代码灵活,但效率低
i小桑
浙公网安备 33010602011771号