Java中数组复制的几种方法
2018-03-12 01:08
316 查看
/** * @author zhengbinMac */ public class Test { public static void main(String[] args) { int[] array1 = {1,2,3,4,5}; // 1.通过for循环 int[] array2 = new int[5]; for(int i = 0;i < array1.length;i++) { array2[i] = array1[i]; } for(int i = 0;i < array2.length;i++) { System.out.print(array2[i]); } System.out.println(); //2.通过System.arraycopy() int[] array3 = new int[5]; System.arraycopy(array1, 0, array3, 0, 5); for (int i = 0; i < array3.length; i++) { System.out.print(array3[i]); } System.out.println(); //3.通过Arrays.copyOf() int[] array4 = new int[5]; array4 = Arrays.copyOf(array1, 5); for (int i = 0; i < array4.length; i++) { System.out.print(array4[i]); } System.out.println(); //4.通过Object.clone() int[] array5 = new int[5]; array5 = array4.clone(); for (int i = 0; i < array5.length; i++) { System.out.print(array5[i]); } } }
1.for循环方法:
代码灵活,但效率低。
2.System.arraycopy()方法:
通过源码可以看到,其为native方法,即原生态方法。自然效率更高。
public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length);
3.Arrays.copyOf()方法:
同样看源码,它的实现还是基于System.arraycopy(),所以效率自然低于System.arraycpoy()。
public static < 4000 span class="hljs-keyword">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.Object.clone()方法:
从源码来看同样也是native方法,但返回为Object类型,所以赋值时将发生强转,所以效率不如之前两种。
protected native Object clone() throws CloneNotSupportedException;
相关文章推荐
- Java中数组复制的几种方法
- JAVA中数组复制的几种方法
- Java中数组复制的几种方法
- java中几种复制数组的方法比较
- JAVA语言的几种数组复制方法
- Java语言的几种数组复制方法
- Java中数组复制的几种方法
- Java复制数组的几种方法
- Java中数组复制的几种方法
- Java基础:数组Array转成List的几种方法
- java 运用数组常用的几种排序方法
- 比较C#中几种常见的复制字节数组方法的效率[转]
- java 数组复制的方法
- java数组复制的简单方法(一)
- Java基础:数组Array转成List的几种方法
- JAVA中复制数组的方法
- Java基础:数组Array转成List的几种方法
- C# 中数组的复制的几种方法
- Java基础:数组Array转成List的几种方法
- java复制数组方法