测试用例(jdk版本:oracle 1.6.0_31)
public class TestCloneable{
public TestCloneable clone(){
return new TestCloneable();
}
}
public static void main(String[] args) {
TestCloneable testObj = new TestCloneable();
TestCloneable testObj2 = new TestCloneable();
System.out.println(testObj.clone());
Hashtable<Integer, TestCloneable> ht = new Hashtable<Integer, TestCloneable>();
ht.put(1, testObj);
ht.put(2, testObj2);
System.out.println(ht.clone());
HashMap<Integer, TestCloneable> hm = new HashMap<Integer, TestCloneable>();
hm.put(1, testObj);
hm.put(2, testObj2);
System.out.println(hm.clone());
}
这些行都不会在运行时给出 CloneNotSupportedException,这与克隆方法的 java 规范相矛盾:
/**
* @exception CloneNotSupportedException if the object's class does not
* support the Cloneable
interface. Subclasses ...
*/
哪里出错了?
Cloneable
因此,您的班级永远不会调用方法
clone()
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
。
此外,如果您想受益于
clone()
中 clone()
方法的行为,并在对象未实现 Object
时抛出异常,则应在重写的方法 Cloneable
中调用 super.clone()
你们班的。