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

后端 未结 5 539
旧巷少年郎
旧巷少年郎 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.

提交回复
热议问题