java数组的拷贝四种方法:for、clone、System.arraycopy、Arrays.copyof

public class Test1 {

	public static void main(String[] args) {

		int[] arr1 = {0, 1, 2, 3, 4, 5, 6};
int[] arr2 = new int[7]; // for循环
for ( int i = 0; i < arr1.length; i++ ) {
arr2[i] = arr1[i];
}
for ( int i = 0; i <arr2.length; i++ ) {
System.out.print(arr2[i]); // 0123456
}
System.out.println(); //clone方法复制数组
int[] arr3 = new int[7];
arr3 = arr1.clone();
for ( int i = 0; i < arr3.length; i++ ) {
System.out.print(arr3[i]); // 0123456
}
System.out.println(); // System.arraycopy方法
int[] arr4 = new int[7];
System.arraycopy(arr1, 0, arr4, 1, 3);
for ( int i = 0; i < arr4.length; i++ ) {
System.out.print(arr4[i]); // 0012000
}
System.out.println(); // Arrays.copyOf方法
int[] arr5 = Arrays.copyOf(arr1, 2);
for ( int i = 0; i < arr5.length; i++ ) {
System.out.print(arr5[i]); // 01
}
}
}

先看看System.arraycopy()的声明:

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

  src - 源数组。
  srcPos - 源数组中的起始位置。
  dest - 目标数组。
  destPos - 目标数据中的起始位置。
  length - 要复制的数组元素的数量。

该方法用了native关键字,说明调用的是其他语言写的底层函数。

再看Arrays.copyOf()

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)?(T[]) new Object[newLength]:(T[])
Array.newInstance(newType.getComponentType(), newLength);System.arraycopy(original,0, copy,0,
Math.min(original.length, newLength));
return copy;
}

 该方法对应不同的数据类型都有各自的重载方法
  original - 要复制的数组
  newLength - 要返回的副本的长度
  newType - 要返回的副本的类型
 仔细观察发现,copyOf()内部调用了System.arraycopy()方法

区别在于:

  1. arraycopy()需要目标数组,将原数组拷贝到你自己定义的数组里,而且可以选择拷贝的起点和长度以及放入新数组中的位置
  2. copyOf()是系统自动在内部新建一个数组,调用arraycopy()将original内容复制到copy中去,并且长度为newLength。返回copy; 即将原数组拷贝到一个长度为newLength的新数组中,并返回该数组。

总结

Array.copyOf()可以看作是受限的System.arraycopy(),它主要是用来将原数组全部拷贝到一个新长度的数组,适用于数组扩容。

最新文章

  1. 每周一书-《鸟哥的Linux私房菜基础学习篇(第四版)》台湾原版,你想要吗?
  2. 如何删除xcode项目中不再使用的图片资源
  3. iOS - UIButton设置文字标题下划线以及下划线颜色
  4. ubuntu12.04 登录黑屏
  5. 蒋鑫:为什么 Git 比 SVN 好
  6. pg_stat_statements
  7. list和map的区别
  8. 201521123088《Java程序设计》第12周学习总结
  9. 【一天一道LeetCode】#88. Merge Sorted Array
  10. IntelliJ IDEA 配置maven
  11. python之函数初识
  12. Spark 介绍
  13. A&gt;B等CSS选择器
  14. .NET本质论 实例
  15. Delphi SetParent 嵌入其他应用程序
  16. 17. Letter Combinations of a Phone Number (backtracking)
  17. jmeter接口测试4-使用数据库mysql构造参数
  18. saltstack系列1之salt-api配置与使用
  19. 3.4 Templates -- Displaying A List of Items(展示一个集合)
  20. js-jQuery对象与dom对象相互转换(转载)

热门文章

  1. Go学习笔记04-函数
  2. 【技术与商业案例解读笔记】095:Google大数据三驾马车笔记
  3. 安利一个_Java学习笔记总结
  4. focus()无效问题
  5. 解决vaio s13笔记本 ubuntu重启卡屏问题
  6. Linux:Day6(上) egrep、条件测试
  7. matlab 整局-部视知觉实验(读取excel点阵设计图替换数据)
  8. Ubuntu 14.04 安装配置备忘录
  9. Java NIO5:通道和文件通道
  10. Java NIO4:缓冲区Buffer(续)