Why can't I clone 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"));
If I use HashMap
instead of ConcurrentHashMap
, it works.
The clone()
method on AbstractMap
is not meant for copying, it is an internal method, note the protected keyword.
protected Object clone() throws CloneNotSupportedException {
HashMap
happens to have a public clone(),
but this does not mean you should use it, this is discussed further by Effective Java: Analysis of the clone() method
A more flexible way to create copies of collections is via the copy-constructors. These have advantage of creating any Map implementation from any other.
/**
* 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"));