Search code examples
javaobjectclone

Cloning objects


For the purposes of making a copy of an object and getting access to its data, what is better and why?

1. Create a new object and initialize it with the data you want to clone through the constructor

 HashSet<String> myClone = new HashSet<String>(data);

2. Clone object as is and cast it to the type you believe it to be

 HashSet<String> myClone = (HashSet<String>) data.clone();

Solution

  • Definitely use a copy constructor - clone() is really quite broken (at least most people agree so.) See here for details.