Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does clone method on array a deep or a shallow copy?

Tags:

java

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?

like image 338
code-gijoe Avatar asked Apr 12 '12 14:04

code-gijoe


People also ask

Does clone make a shallow or deep copy?

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.

Is clone method deep copy?

Note − By default, the clone() method does a shallow copy.

Is array copy of a deep 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.

What is clone method in an array?

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.


3 Answers

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.

like image 71
MTilsted Avatar answered Oct 01 '22 20:10

MTilsted


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/

like image 33
woolcock66 Avatar answered Oct 01 '22 21:10

woolcock66


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.

like image 40
Richard Chambers Avatar answered Oct 01 '22 22:10

Richard Chambers