开发者

use case for clone()

开发者 https://www.devze.com 2022-12-21 06:23 出处:网络
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.

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:

  1. 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.

  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号