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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.