views:

153

answers:

3

Hello,

I want to make a Deep Copy of some Object[] and ArrayList How can i do that (without looping , and calling clone)

There aren't standard utils for doing this?

Thanks João

+1  A: 

You can serialize the whole array and then deserialize it into a new variable. This effectively does a deep copy.

Otherwise you would have to implement a deep copy by yourself.

codymanix
But i think that is worse than looping by elements isn't it?Regards
Joao Ismael
Only if the ArrayList contents are serializable
naikus
Serializing will be slower than manual looping but is much simpler, especially if you have a complex object hierarchy.
codymanix
A: 

how about System.arrayCopy?

mohammad shamsi
That makes a shallow copy.
Stephen P
+1  A: 

None trivial objects need to provide some to support copying: even if that is in the form of implementing Clone or Serialize. This is more or less why there is no built in method and the loop is unavoidable.

If it is all your own code then I would recommend a copy constructor over either clone or serialize/deserialize as that is more OO; you ask the object to create its own copy rather than ask the JVM to do a low level copy. Such code is very simple and easy to read so hopefully cheaper to maintain in the long run:

public class Widget {
   private int x = 0;
   public Widget(Widget copyMe){
       this.x = copyMe.x;
       // ...
   }
   // ....
}

You still need a loop of course to loop over the old collection invoking the copy constructor to populate the new collection. There is a book called Effective Java which goes into a lot of detail about the pitfalls of clone and serialize that I highly recommend.

There are some systems which really need very high speed copying and sorting and the like (e.g. Hadoop). Such systems put the onus on the developer to support a custom binary format (e.g. byte[] getAsBytes() / public Widget(byte[] fromBytes) ). Packing many objects turned into byte[] into a larger array means that they can be all copied at once very fast using System.arraycopy on the big array. The JVM is going to do System.arraycopy as a low level memory copy. You are still going to need the loop to deserialize the objects from the chunk of bytes after the copy.

In general the compiler and jvm tend to optimize basic code very well so unless you actually measure that you have a real and measurable performance issue then a very simple loop with a very readable copy constructor is going to be the best long term approach.

simbo1905