There seems to be a lot of confusion and different opinions on this out there ([1] and other sources) on whether Arrays.copyOf
will produce a deep or shallow copy.
This test suggests that the copy is 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 suggests 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
Is the solution simply that a deep copy of the top-level dimension is made, but other dimensions are a shallow copy? What is the truth?
[1] How do I do a deep copy of a 2d array in Java?
See Question&Answers more detail:os