Use Case for Cloning ()

I have never seen the clone () method used for use in any real code. I read about it and felt that using it could make the code very cumbersome. Is there a specific use case for the clone () method? Under what circumstances would clone () be needed and why would the use of a regular constructor not be sufficient?

+4
source share
2 answers

clone very convenient to create protective copies of arrays passed to methods or constructors (since all types of arrays are Cloneable , and the signature for clone() is covariant, so boolean[].clone() actually returns boolean[] and not Object ). This is the only really good use I've seen for ten years, though ...

+3
source

Josh Bloch in Effective Java also does not recommend using the clone () method.

There are several problems with this method:

1) If the cloned object has not only fields of a primitive type, but also fields of objects, then the cloned object will receive only references to these objects, but not to real cloned objects. To avoid this, all internal objects must also be cloned.

2) If you create a subclass of the cloneable class, then it is also cloned (even if you do not want it). This is why you should properly override the clone () method to avoid possible problems.

When you should use it: never, if possible. You must use it very carefully. If all the fields in the object that you want to make cloneable are of a primitive type, then this is not dangerous. In all other cases, think twice before using it.

+2
source

Source: https://habr.com/ru/post/1301955/


All Articles