use case for clone()

孤人 提交于 2019-12-10 16:14:59

问题


I have never seen clone() method put to use 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?


回答1:


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




回答2:


Josh Bloch in Effective Java also doesn't recommend to use clone () method.

There are several problems with this method:

1) If cloneable object have 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.



来源:https://stackoverflow.com/questions/2306332/use-case-for-clone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!