I did a quick google on implementing clone() in Java and found:
http://www.javapractices.com/topic/TopicAction.do?Id=71
It has the following comment:
copy constructors and static factory methods provide an alternative to clone, and are much easier to implement.
All I want to do is make a deep copy. Implementing clone() seems to make a lot of sense, but this highly google ranked article makes me a bit afraid.
Here are the issues that I've noticed:
Copy constructors don't work with Generics.
Here's some pseudo-code that won't compile.
public class MyClass<T>{
..
public void copyData(T data){
T copy=new T(data);//This isn't going to work.
}
..
}
Sample 1: Using a copy constructor in a generic class.
Factory methods don't have standard names.
It's quite nice to have an interface for reusable code.
public class MyClass<T>{
..
public void copyData(T data){
T copy=data.clone();//Throws an exception if the input was not cloneable
}
..
}
Sample 2: Using clone() in a generic class.
I noticed that clone is not a static method, but wouldn't it still be necessary to make deep copies of all the protected fields? When implementing clone(), the extra effort to throw exceptions in non-cloneable subclasses seems trivial to me.
Am I missing something? Any insights would be appreciated.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…