克隆ConcurrentHashMap

Moh*_*vaf 2 java clone concurrenthashmap

为什么我不能克隆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"));
Run Code Online (Sandbox Code Playgroud)

如果我使用HashMap而不是ConcurrentHashMap,它的工作原理.

Ada*_*dam 9

clone()对方法AbstractMap并不意味着用于复制,它是一个内部方法,注意保护关键字.

protected Object clone() throws CloneNotSupportedException {
Run Code Online (Sandbox Code Playgroud)

HashMap碰巧有一个公开,clone(),但这并不意味着你应该使用它,这将由Effective Java进一步讨论:clone()方法的分析

创建集合副本的更灵活方法是通过复制构造函数.这些优点是可以从任何其他地方创建任何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) {
Run Code Online (Sandbox Code Playgroud)

例如

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"));
Run Code Online (Sandbox Code Playgroud)