Java-Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别
2016-10-25 09:18
555 查看
如果我们想拷贝一个数组,我们可能会使用System.arraycopy()或者Arrays.copyof()两种方式。在这里,我们将使用一个比较简单的示例来阐述两者之间的区别。
1、示例代码:
System.arraycopy()
运行结果:
Arrays.copyof()
运行结果:
2、两者间的主要区别
两者的区别在于,Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。
如果我们看过Arrays.copyOf()的源码就会知道,该方法的底层还是调用了System.arrayCopyOf()方法。
1、示例代码:
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));
运行结果:
[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));
运行结果:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3]
2、两者间的主要区别
两者的区别在于,Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。
如果我们看过Arrays.copyOf()的源码就会知道,该方法的底层还是调用了System.arrayCopyOf()方法。
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中System.arraycopy() 和 Arrays.copyOf()两者之间的区别?
- 在Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别
- java.lang.System.arraycopy() 与java.util.Arrays.copyOf()的区别
- System.arraycopy()和Arrays.copyOf()的区别
- Java方法之--System.arraycopy方法和Arrays.copyOf()
- Arrays.copyOf和System.arraycopy之间的区别
- Arrays.copyof(···)与System.arraycopy(···)区别
- Arrays.copyof(···)与System.arraycopy(···)区别
- Arrays.copyof(···)与System.arraycopy(···)区别
- System.arraycopy()和Arrays.copyOf()的区别
- java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.copyof
- java中的System.copyof()与Array.copyof()区别
- Java方法System.arraycopy方法和Arrays.copyOf()
- System.arraycopy()和Arrays.copyOf()的区别
- java中System.copyArray与Arrays.copyof区别
- System.arraycopy 和 Arrays.copyOf()的区别
- System.arraycopy()和Arrays.copyOf()的区别
- Java方法-System.arraycopy方法和Arrays.copyOf()
- Java方法之--System.arraycopy方法和Arrays.copyOf()
- Java方法之--System.arraycopy方法和Arrays.copyOf()