java – Arrays. Does copyof generate a shallow or deep copy?

About arrays There seems to be a lot of confusion and different opinions on whether copyof will produce deep and shallow copies ([1] and other sources)

The test showed that the copy was deep:

String[] sourceArray = new String[] { "Foo" };
String[] targetArray = java.util.Arrays.copyOf( sourceArray,1 );

sourceArray[0] = "Bar";

assertThat( targetArray[0] ).isEqualTo( "Foo" ); // passes

This test shows that the copy is shallow:

String[][] sourceArray = new String[][] { new String[] { "Foo" } };
String[][] targetArray = java.util.Arrays.copyOf( sourceArray,1 );

sourceArray[0][0] = "Bar";

assertThat( targetArray[0][0] ).isEqualTo( "Foo" ); // fails

The solution only makes a deep copy of the top-level dimension, but the other dimensions are shallow copies? What is the truth?

[1] How do I do a deep copy of a 2d array in Java?

Solution

It produces a shallow copy, a new array containing "old" references (for the same object, those are not copied)

In particular, if you have nested arrays, those will not be copied You will get a new array whose "top level" points to the same "second level" array Any changes in these nested arrays will be reflected in the copy and the original content

No, No When you assign a new object to the "original" array, this does not affect the copy After all, this is a copy

This is the same:

String x = "foo";
String y = x;
x = "bar";

assertEquals(y,"foo");

There is no "deep copy" here

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
分享
二维码
< <上一篇
下一篇>>