prasanth prasanth - 1 year ago 98
Java Question

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

I am having a final class

. I copied an array of
objects using
and when i changed a
object in copied array, it gets reflected in the original array.

public final class NameAndValue
public String name;
public String value;

public NameAndValue()


public NameAndValue(String name,String value)
{ = name;
this.value = value;

public class Main
public static void main(String[] args)
NameAndValue[] nv = new NameAndValue[4];
nv[0] = new NameAndValue("A", "1");
nv[1] = new NameAndValue("B", "2");
nv[2] = new NameAndValue("C", "3");
nv[3] = new NameAndValue("D", "4");

NameAndValue[] nv2 = new NameAndValue[4];
System.arraycopy(nv, 0, nv2, 0, 2);
nv2[2] = new NameAndValue("Y","25");
nv2[3] = new NameAndValue("Z","26");

for (int i = 0; i < 2; i++)
NameAndValue[] nv3 = new NameAndValue[4];
System.arraycopy(nv2, 0, nv3, 0, 4);
nv3[2].value = String.valueOf(i);
nv3[3].value = String.valueOf(i+1);


I am getting output as,


I should have got output as 25 and 26 in all the cases,right?? why does it get changed??

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download