2012-03-27 22 views
0

測試用例(JDK的版本:ORACLE 1.6.0_31)的對象clone()方法不拋出的RuntimeException被稱爲上類未實現了Cloneable

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

哪裏出錯?

+2

在使用克隆嗎?一般來說,克隆有點破損。 – 2012-03-27 15:35:02

+0

一般來說。我的意思是它是我在使用克隆中的錯誤還是在jdk中的一些錯誤? – Egor 2012-03-27 15:38:27

回答

3

根據javadocs for hashmap

clone() 
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned. 

所以該方法clone()永遠不會叫上你的課。

而且,如果你想從clone()方法的行爲中獲益Object,並有當目標沒有實現Cloneable異常拋出,你應該在你的類的overrided方法clone調用super.clone()

+0

謝謝!正確的測試用例將是公共類TestCloneable公用類TestCloneable公用類TestCloneable clone()拋出CloneNotSupportedException異常{ \t \t TestCloneable tc =(TestCloneable)super.clone(); \t \t return tc; \t} } – Egor 2012-03-27 16:48:54

相關問題