Java中数组复制的几种方法
来源:互联网 发布:大数据的弱点有几方面 编辑:程序博客网 时间:2024/05/16 01:53
http://www.cnblogs.com/zhengbin/p/5671403.html
1 /** 2 * @author zhengbinMac 3 */ 4 public class Test { 5 public static void main(String[] args) { 6 int[] array1 = {1,2,3,4,5}; 7 // 1.通过for循环 8 int[] array2 = new int[5]; 9 for(int i = 0;i < array1.length;i++) {10 array2[i] = array1[i];11 }12 for(int i = 0;i < array2.length;i++) {13 System.out.print(array2[i]);14 }15 System.out.println();16 //2.通过System.arraycopy()17 int[] array3 = new int[5];18 System.arraycopy(array1, 0, array3, 0, 5);19 for (int i = 0; i < array3.length; i++) {20 System.out.print(array3[i]);21 }22 System.out.println();23 //3.通过Arrays.copyOf()24 int[] array4 = new int[5];25 array4 = Arrays.copyOf(array1, 5);26 for (int i = 0; i < array4.length; i++) {27 System.out.print(array4[i]);28 }29 System.out.println();30 //4.通过Object.clone()31 int[] array5 = new int[5];32 array5 = array4.clone();33 for (int i = 0; i < array5.length; i++) {34 System.out.print(array5[i]);35 }36 }37 }
1.for循环方法:
代码灵活,但效率低。
2.System.arraycopy()方法:
通过源码可以看到,其为native方法,即原生态方法。自然效率更高。
1 public static native void arraycopy(Object src, int srcPos,2 Object dest, int destPos,3 int length);
3.Arrays.copyOf()方法:
同样看源码,它的实现还是基于System.arraycopy(),所以效率自然低于System.arraycpoy()。
1 public static int[] copyOf(int[] original, int newLength) {2 int[] copy = new int[newLength];3 System.arraycopy(original, 0, copy, 0,4 Math.min(original.length, newLength));5 return copy;6 }
4.Object.clone()方法:
从源码来看同样也是native方法,但返回为Object类型,所以赋值时将发生强转,所以效率不如之前两种。
0 0
- Java中数组复制的几种方法
- Java中数组复制的几种方法
- JAVA中数组复制的几种方法
- Java中数组复制的几种方法
- Java复制数组的几种方法
- java中复制数组的几种方式
- java中数组复制的几种常见用法
- 数组复制的几种常用方法
- 数组的几种复制方法
- java中复制数组的方法
- java中复制数组的方法
- JAVA中复制数组的方法
- Java中数组复制的2种方法
- JAVA中复制数组的五种方法
- Java中数组复制的四种方法
- JAVA中复制数组的五种方法
- JAVA 中数组的几种排序方法 标准的!
- JAVA 中数组的几种排序方法
- Python中函数的参数
- ab压力测试的轻量级具体做法
- LA 7243 Frogs [容斥定理]
- index
- 九度 OJ 1449 确定比赛名次
- Java中数组复制的几种方法
- Mac下删除文件夹隐藏文件.DS_Store且不再生
- 【Hadoop】在执行job时,hadoop与linux和win7之间的交互出现IO拒绝访问的解决方案
- SQL基础笔记(二)
- 软件开发简述
- 双调查找
- SQL基础笔记(三)
- WinINet
- Java就业指导