aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Deep copy/clone method for arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Deep copy/clone method for arrays" Watch "Deep copy/clone method for arrays" New topic
Author

Deep copy/clone method for arrays

Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Is there a deep copy/clone method for arrays? What I mean is a method which will clone a multidimensional array so that each array element is a reference to a new array object, and not another reference to a shared array. As far as I can tell this is how the Arrays.copyOf() and clone() methods work:



Thanks!


All code in my posts, unless a source is explicitly mentioned, is my own.
reji singh
Ranch Hand

Joined: Apr 06, 2009
Posts: 52
Hi Ruben,

I believe there is none for deep cloning of multi-dimensional arrays at the moment.

It might be due to the dimension of arrays that will limit this functionality to be put in a single method.



For 2D , you can loop through each row and cloning them one-by-one .

Thanks
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Thanks for your answer, Reji. I think there would be ways to implement a method to work with any multidimensional array. You just need to iterate over each element, check whether it's an array, and do this recursively. It might get a little complicated though, since you would need to keep track of every included subarray and the dimensions for each element, so that you can go back and instantiate a new array of whichever dimension is needed. But I don't see any technical limitations.

I would be extremely surprised if someone hasn't already implemented this. Maybe there is a method which does this somewhere in the API which we are missing.
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8717
interesting topic, not on the exam


Eliminate fossil fuel subsidies. (If you're not on the edge, you're taking up too much room.)
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Yeah, thanks for pointing that out Bert. Maybe I should have used the Basic (or Intermediate) Java forum.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Deep copy/clone method for arrays
 
Similar Threads
clone() shallow copy in arrays?
Cloning of Multidimensional Array
Question about clone a Hashtable
Printing in Array in Ascending order
Cloning 1D and 2D array