2

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

3
  • A deep copy will have a conceptual loop of some kind. The question is whether it's hidden from view inside a util or not. Commented Jul 20, 2010 at 15:52
  • Dupe? stackoverflow.com/questions/64036/… Commented Jul 20, 2010 at 15:56
  • Are you going to modify the copy? Commented Jul 20, 2010 at 15:58

2 Answers 2

2

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.

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

Comments

2

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.

3 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.