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

后端 未结 5 550
旧巷少年郎
旧巷少年郎 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题