Reputation: 571
Test case (jdk version: 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());
}
None of these lines gives CloneNotSupportedException in runtime which contradicts java specification on clone method:
/**
* @exception CloneNotSupportedException if the object's class does not
* support the
Cloneable
interface. Subclasses ...
*/
Where is mistake?
Upvotes: 0
Views: 382
Reputation: 38168
According to javadocs for hashmap :
clone()
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
So the method clone()
is never called on your class.
Moreover, if you want to benefit from the behavior of the clone()
method in Object
and have an exception thrown when the object doesn't implement Cloneable
, you should call super.clone()
in the overrided method clone
of your class.
Upvotes: 3