Should I use the Clone method in java?

I heard that you should avoid this in your code, but for some reason it was implemented, so is there a case where using it is actually a good (or not bad) choice, or should I always avoid it?

+3


source to share


2 answers


Josh Bloch answered this beautifully:



If you read the article on cloning in my book, especially if you read between the lines, you will know that I think the clone is deeply broken. There are several design flaws, the biggest of which is that the Cloned Interface has no cloning method. And that means it just doesn't work: doing something cloned doesn't say anything about what you can do about it. Instead, he says something about what he can do internally. It says that if you call super.clone repeatedly it ends up calling the object cloning method, that method will return a copy of the original field.

But it doesn't say anything about what you can do with an object that implements the Cloneable interface, which means you cannot polymorphic a clone. If I have a Cloneable array, you would think that I could run that array and clone each item to make a deep copy of the array, but I can't. You can't do something to Cloneable and call the clone method, because Cloneable doesn't have a public clone method, nor does it have Object. If you are trying to cast to Cloneable and call the clone method, the compiler will say you are trying to call the secure clone method on the object.

It's a shame that Cloneable is broken, but it happens. The original Java APIs were executed very quickly in a tight time frame for closing the market window. The original Java team did an incredible job, but not all APIs are perfect. The cloned is a weak point and I think people should be aware of their limitations.

+3


source


You should always override the clone method based on the object type, the java clone () method doesn't always do what you want.



see deep copy, shallow copy, clone

0


source







All Articles