use case for clone()
I have never seen clone() method put to use开发者_JS百科 in any real code. I was reading about it and felt that its use could make the code very cumbersome. is there any specific use case for the clone() method? Under what circumstances would one have to use clone() and why would the use of normal conctructor not suffice?
clone
is very convenient to make defensive copies of arrays passed to methods or constructors (as all array types are Cloneable
, and the signature for clone()
is covariant so that boolean[].clone()
actually returns a boolean[]
rather than an Object
). That's the only really good use I've seen of it in ten years, though...
Josh Bloch in Effective Java also doesn't recommend to use clone () method.
There are several problems with this method:
If cloneable object has not only primitive type fields but also object fields, then cloned object will receive just references to those objects but not real cloned objects. To avoid this all inner objects should be cloneable too.
If you make a subclass of cloneable class, then it's cloneable too (even if you don't want). That's why you should override clone() method in a proper way to avoid possible problems.
When you should use it: never if possible. You should use it very carefully. If all fields in object you want to make cloneable are of primitive type then it's not dangerous. In all other cases think twice before using it.
精彩评论