[java]Arrays.copyOf() VS System.arrayCopy()
2016-02-19 17:01
519 查看
If we want to copy an array, we can use either
Output:
Arrays.copyOf()
Output:
2. The Major Difference
The difference is that
If we read the source code of Arrays.copyOf(), we can see that it uses
System.arraycopy()or
Arrays.copyOf(). In this post, I use a simple example to demonstrate the difference between the two. 1. Simple Code Examples System.arraycopy()
int[] arr = {1,2,3,4,5};
int[] copied = new int[10];
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
System.out.println(Arrays.toString(copied));
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
Arrays.copyOf()
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied)); copied = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(copied));
Output:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]
2. The Major Difference
The difference is that
Arrays.copyOfdoes not only copy elements, it also creates a new array.
System.arrayCopycopies into an existing array.
If we read the source code of Arrays.copyOf(), we can see that it uses
System.arraycopy().
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;
}
相关文章推荐
- java算法 使用递归计算阶乘
- Java代码检查工具
- Java基础相关
- spring mvc 输入域名跳转首页配置方式
- Springmvc 注解 伪静态(urlrewrite) 配置
- Java UDP 简单实例
- 【Java-Reflection】反射获取泛型参数类型
- 使用异或进行简单的密码加密(JAVA实现)
- 使用Eclipse构建Maven项目
- JAVA基础
- Java断点续传
- Spring MVC下 Excel 导入导出(poi)
- JavaCompiler编译的时候有时会返回NULL
- maven构建项目引用spring找不到org.springframework.transaction
- Java 注解实例
- hdu2567 java
- 解决jar包依赖:Spring IO platform推出bom
- JAVA程序的基本结构,标识符和关键字
- hdu2566 Java
- 学习SpringMVC 笔记