为什么我无法克隆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
,则可行。
答案 0 :(得分:9)
clone()
上的AbstractMap
方法不适用于复制,它是一种内部方法,请注意受保护的关键字。
protected Object clone() throws CloneNotSupportedException {
HashMap
恰好有公开clone(),
,但这并不意味着您应该使用它,Effective Java: Analysis of the clone() method
创建集合副本的更灵活方法是通过复制构造函数。这些优点是可以从任何其他地方创建任何Map实现。
/**
* Creates a new map with the same mappings as the given map.
*
* @param m the map
*/
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
e.g。
ConcurrentHashMap<String, String> original = new ConcurrentHashMap<String, String>();
original.put("hello", "Salaam");
Map<String, String> copy = new ConcurrentHashMap<>(original);
original.remove("hello");
System.out.println(copy.get("hello"));
答案 1 :(得分:0)
更优雅的方法是执行深度克隆。 如果您执行深度克隆,则可能存在一种情况,其中您仅复制存储在并发哈希图中的引用,而不是实际对象。这就是为什么在这种情况下,最好使用深度克隆来克隆对象图中的对象的原因。进行深度克隆的最简单方法之一是使用apache通用lang库-SerializationUtils#clone。
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
您可以使用SerializationUtils类的克隆api进行深度克隆,如下所示-
ConcurrentHashMap<String, Vertex> transposeVertexMap = (ConcurrentHashMap<String, Vertex>) SerializationUtils.clone(vertexMap);