为什么我不能克隆
如果我使用
ConcurrentHashMap
?ConcurrentHashMap<String, String> test = new ConcurrentHashMap<String, String>();
test.put("hello", "Salaam");
ConcurrentHashMap<String, String> test2 = (ConcurrentHashMap<String, String> ) test.clone();
System.out.println(test2.get("hello"));
如果我使用
HashMap
而不是 ConcurrentHashMap
,它可以正常工作。
HashMap
不同,ConcurrentHashMap
没有实现Cloneable
。这一事实凸显了你的代码无法编译,即该方法不可用!!! - AndreasCloneable
,并不意味着你支持clone
,而支持clone
也不需要你实现Cloneable
。Cloneable
实际上没有clone
作为公共方法。这是clone
设计的一种奇怪缺陷。 - user2357112clone
需要实现Cloneable
接口,@user2357112。"在一个没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法会导致抛出 CloneNotSupportedException 异常。" - https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html - Lew Blochclone
实现中不使用Object :: clone
(有时是合理的),则不需要实现Cloneable
。这甚至不像Comparable
,如果您在不实现Comparable
的情况下实现了compareTo
,则会失去所有接受Comparable
参数的库方法。使用clone
的任何内容都不需要Cloneable
,因为您无法clone
一个Cloneable
。 - user2357112