I'm not sure if the following will result in deep or shallow copy?
public void viewImages(final String[] instancesFilename) {
String[] instances = (String[])instancesFilename.clone();
}
Is there a simple and fast way to deep copy a string array?
Default version of clone method creates the shallow copy of an object. To create the deep copy of an object, you have to override clone method. Shallow copy is preferred if an object has only primitive fields. Deep copy is preferred if an object has references to other objects as fields.
Note − By default, the clone() method does a shallow copy.
No, it does not. When you assign a new object to the "original" array, this does not affect the copy. It is, after all, a copy.
When the clone method is invoked upon an array, it returns a reference to a new array which contains (or references) the same elements as the source array. So in your example, int[] a is a separate object instance created on the heap and int[] b is a separate object instance created on the heap.
Strings in Java are imutable(Can't change their value). So there is no detectable difference between a deep and shallow copy when copying strings.
And just to further reference: The copy will be shallow but that should not be a problem since strings are imutable.
Oh and funny fact: Strings can't be cloned with the clone method, so if you try to do a deep copy of strings with the clone method, you will get a CloneNotSupportedException.
The array class also has the copyOf method. This is generally what I use for creating copies of arrays. Heres and explanation of all of the differences: http://forum.codecall.net/topic/49450-copying-arrays/
Here is an interesting article discussing using serialization to make deep copies.
The objects in the call graph do need to support serialization however in many business types of 3 Tier applications, that necessity is there.
The article provides a discussion of deep copy and shallow copy with some diagrams.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With