java – System. Arraycopy() copy objects or reference objects?
•
Java
I have a final class nameandvalue I use system Arraycopy () copies an array of nameandvalue objects. When I change the nameandvalue object in the copied array, it is reflected in the original array
public final class NameAndValue { public String name; public String value; public NameAndValue() { } public NameAndValue(String name,String value) { this.name = 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,nv2,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,nv3,4); nv3[2].value = String.valueOf(i); nv3[3].value = String.valueOf(i+1); System.out.println(nv2[2].value); System.out.println(nv2[3].value); System.out.println("-----------------------"); } } }
The output I get,
0 1 ----------------------- 1 2 -----------------------
In all cases, I should output 25 and 26, right? Why did it change?
Solution
For reference, this is a shallow copy Surprisingly, the docs don't say that explicitly only implicitly introduces copying array elements, not recursively copying what they reference
This is the same as before:
NameAndValue nv1 = new NameAndValue("A","1"); NameAndValue nv2 = nv1; nv2.value = "4"; System.out.println(nv1.value); // 4
Each array element is like nv1 and nv2 vars above Just as nv1 and nv2 reference (point to) the same underlying object, so do array entries, including when they are copied from one array to another
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码