Java System.arraycopy 针对同一数组和两个数组

来源:互联网 发布:开淘宝店要多少钱押金 编辑:程序博客网 时间:2024/05/21 08:41
public class TestSystemArrayCopy {public static void main(String[] args) {//定义数组int [] arr1 = new int[20];//初始化数组for (int i = 0 ;i < 20; i++) {arr1[i] = i;}//show arrayfor (int i: arr1) {System.out.print(i+ " ");}System.out.println();//同一数组的 copySystem.arraycopy(arr1, 6, arr1, 2, 10);for (int i: arr1) {System.out.print(i+ " ");}System.out.println();}}0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0 1 6 7 8 9 10 11 12 13 14 15 12 13 14 15 16 17 18 19 

测试结果:对于同一个数组的拷贝System.arraycopy(arr, a, arr, b, c)(a, b , c 为arr 的合法下标)

结果为:arr[b] ~ arr[b + c -1] 替换为 arr[a] ~ arr[a + c - 1]

将数组 arr 中 下标从 b 开始的(包括arr[b])的c个元素 替换为从a开始(包括arr[a])的c个元素


移除数组某一下标的的值:

public class TestSystemArrayCopy {public static void main(String[] args) {//定义数组int [] arr1 = new int[20];//初始化数组for (int i = 0 ;i < 10; i++) {arr1[i] = i;}//show arrayfor (int i: arr1) {System.out.print(i+ " ");}System.out.println();//移除下标为6的值System.arraycopy(arr1, 6 + 1, arr1, 6, 10);for (int i: arr1) {System.out.print(i+ " ");}System.out.println();}}0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 7 8 9 0 0 0 0 0 0 0 0 0 0 0 

两个数组的拷贝:

public class TestSystemArrayCopy {public static void main(String[] args) {//定义数组int [] arr1 = new int[20];int [] arr2 = new int[20];//初始化数组for (int i = 0 ;i < 20; i++) {arr1[i] = i;arr2[i] = 2 * i;}//show arrayfor (int i: arr1) {System.out.print(i+ " ");}System.out.println();for (int i: arr2) {System.out.print(i+ " ");}System.out.println();//数组copySystem.arraycopy(arr1, 5, arr2, 2, 10);for (int i: arr1) {System.out.print(i+ " ");}System.out.println();for (int i: arr2) {System.out.print(i+ " ");}System.out.println();}}0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0 2 5 6 7 8 9 10 11 12 13 14 24 26 28 30 32 34 36 38 
测试结果:System.arraycopy(arr1, a, arr2, b, c)
                 arr1 不变 

                 arr2: arr2[b] ~ arr2[b + c -1] 替换为 arr1[a] ~ arr1[a + c - 1]

将数组 arr2 中 下标从 b 开始的(包括arr2[b])的c个元素 替换为从arr1 中 a开始(包括arr1[a])的c个元素


0 0
原创粉丝点击