System.arraycopy 方法

 
import java.util.Arrays;

public class SystemArrayCopyTest {

  public static void main(String[] args) {

    int[] test1 = new int[]{2, 3, 4, 5, 6, 7, 8};

    System.out.println("test1--->"+Arrays.toString(test1));

    int[] test2 = new int[test1.length];

    System.arraycopy(test1, 0, test2, 0, test1.length);

    System.out.println("tset2--->"+Arrays.toString(test2));

    test2[0] = 8;
    test2[1] = 9;

    System.out.println("tset2--->"+Arrays.toString(test2));

    
    ///////////////////////////////////////////////////////////////////////////////////////
    //只修改了复制来的副本数组,原数组没有变,此时是值传递

    char[][] one = new char[][]{{'a', 'b'}, {'c', 'd'}, {'e', 'f'}};

    System.out.println("one---->"+Arrays.toString(one[0]));

    char[][] another = new char[2][2];
    
    System.arraycopy(one, 0, another, 0, 2);

    System.out.println("another---->"+Arrays.toString(another[0]));

//         another[0][0] = 'x' ;      another[0][1] = 'y' ;

    one[0][0] = 'x';
    one[0][1] = 'y';

    System.out.println(Arrays.toString(one[0]));

    System.out.println(Arrays.toString(another[0]));

     /*   java其实没有二维数组的概念,平常实现的二维数组只是元素是一维数组的一维数组,而数组也是引用类型,
     继承自Object类。
          数组是new出来的。这些性质也就导致arraycopy()二维数组时出现的问题。
          如果是一维数组,那么元素都是基础类型(如int,double等),使用arraycopy()方法后,是把原数组的
     值传给了新数组,属于值传递。
          而如果是二维数组,数组的第一维装的是一个一维数组的引用,第二维里是元素数值。
          对二维数组应用arraycopy()方法后,第一维的引用被复制给新数组的第一维,也就是两个数组的第一维都
     指向相同的“那些数组”。
          而这时改变其中任何一个数组的元素的值,   其实都修改了“那些数组”的元素的值,所以原数组和新
     数组的元素值都一样了。       * */
  }

}

你可能感兴趣的:(System.arraycopy 方法)