5

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?

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

6 Comments

The author is asking to copy String[], not String. The elements of instancesFilename could be changed later from the outside, so the OP wants to create a copy of the array.
Well it's detectable (are the references the same) but if you're using the strings properly, it shouldn't be significant.
@PhilippReichart: But the OP is already performing a clone - "deep copy" vs "shallow copy" in that context can only be about whether the strings are cloned or not - and as this answer states, it's almost always unimportant.
... But the String can be intern()'d, which would make kind of a shallow copy :\
Your clone method will create a new independent array with new references to the same string objects. Which most likely is what you want/need. But your new references will point to the same String objects as the original Array. But I can't imagine why this would be a problem.
|
2

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/

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.