System.arraycopy()从指定源数组中复制一个数组
2016-09-27 18:44
344 查看
System类提供了一个arraycopy()方法
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
该方法用于从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。从 src 引用的源数组到 dest 引用的目标数组,数组组件的一个子序列被复制下来。被复制的组件的编号等于 length 参数。源数组中位置在 srcPos 到 srcPos+length-1 之间的组件被分别复制到目标数组中的 destPos 到 destPos+length-1 位置。
如果参数 src 和 dest 引用相同的数组对象,则复制的执行过程就好像首先将 srcPos 到 srcPos+length-1 位置的组件复制到一个带有 length 组件的临时数组,然后再将此临时数组的内容复制到目标数组的 destPos 到 destPos+length-1 位置一样。
方法参数解释
src - 源数组。 srcPos - 源数组中的起始位置。 dest - 目标数组。 destPos - 目标数据中的起始位置。 length - 要复制的数组元素的数量。
方法使用中抛出的异常
IndexOutOfBoundsException - 如果复制会导致对数组范围以外的数据的访问。 ArrayStoreException - 如果因为类型不匹配而使得无法将 src 数组中的元素存储到 dest 数组中。 NullPointerException - 如果 src 或 dest 为 null。
案例
public class SystemDemo { public static void main(String[] args) { int[] arr1 = { 1, 2, 3, 4, 5, 6, 7}; // 打印当前数组 System.out.println(Arrays.toString(arr1)); // 实现数组自我复制,把从索引0开始的3个数字复制到索引为4的位置上 System.arraycopy(arr1, 0, arr1, 4, 3); System.out.println(Arrays.toString(arr1)); // 实现将数组复制到其他数组中,把从索引1开始的3个数据复制到目标的索引为0的位置上 int[] arr2 = new int[7]; System.arraycopy(arr1, 1, arr2, 0, 3); System.out.println(Arrays.toString(arr2)); } }
结果:
相关文章推荐
- System.arraycopy()从指定源数组中复制一个数组
- 使用System.arraycopy()实现数组之间的复制
- java 数组复制:System.arrayCopy 解析
- System.arrayCopy()和普通数组复制之间的效率差别
- System.arraycopy()实现数组之间的复制
- [java]数组复制小结 for 、clone、 System.arraycopy
- 使用System.arraycopy()实现数组之间的复制
- 使用System.arraycopy()实现数组之间的复制
- 使用System.arraycopy()实现数组之间的复制
- 使用System.arraycopy()实现数组之间的复制
- 使用System.arraycopy()实现数组之间的复制
- System.arraycopy 数组复制
- java 数组复制:System.arrayCopy 深入解析
- [java]数组复制小结 for 、clone、 System.arraycopy
- Java数组复制的方法和System.arraycopy
- 使用System.arraycopy()实现数组之间的复制
- 使用System.arraycopy()实现数组之间的复制
- Java—使用System.arraycopy()实现数组之间的复制
- 使用System.arraycopy()实现数组之间的复制
- 使用System.arraycopy()实现数组之间的复制