System.arrayCopy() copies object or reference to object?

后端 未结 5 541
旧巷少年郎
旧巷少年郎 2020-12-16 03:04

I am having a final class NameAndValue. I copied an array of NameAndValue objects using System.arrayCopy() and when i changed a

相关标签:
5条回答
  • 2020-12-16 03:27

    System.arrayCopy() copies object or reference to object?

    Reference, it's a shallow copy. Surprisingly, the docs don't say that explicitly, just implicitly as they only talk about copying array elements, not recursively copying the things they reference.

    It's exactly the same as if you had this:

    NameAndValue nv1 = new NameAndValue("A", "1");
    NameAndValue nv2 = nv1;
    nv2.value = "4";
    System.out.println(nv1.value); // 4
    

    Each array element is like the nv1 and nv2 vars above. Just as nv1 and nv2 reference (point to) the same underlying object, so do the array entries, including when those entries are copied from one array to another.

    0 讨论(0)
  • 2020-12-16 03:27

    It gets changed because both arrays are referencing the same underlying objects still. You could assign a new object to a position in the array and it wouldn't get reflected in the other array, but if you make a modification to the object that both arrays are pointing to, then both will see it differently.

    In this sense, it's pass "reference by value", rather than strictly pass by reference - but the effect you're seeing is because the reference remains the same.

    Copies like this are almost always shallow copies in Java, unless explicitly stated otherwise. This is no exception.

    0 讨论(0)
  • 2020-12-16 03:37

    System.arraycopy is a shallow copy. here's why:

    it uses JNI to use something like memcpy() which just copies the pointers in memory. it's a very fast operation.

    0 讨论(0)
  • 2020-12-16 03:38

    As far as I know arraycopy is a shallow copy. Which means the new array will reference to the addresses of the elements in the old array. So if you adjust a value in one of them, it will reflect on both

    0 讨论(0)
  • 2020-12-16 03:42
        int[] a = {1, 2, 3};
        int[] b = new int[3];
        System.arraycopy(a, 0, b, 0, 3);
        b[1] = 0;
        System.out.println(Arrays.toString(b));
        System.out.println(Arrays.toString(a));
    

    The output is like this: [1, 0, 3] [1, 2, 3]

    0 讨论(0)
提交回复
热议问题