2016-07-17 44 views
1

爲什麼我不能克隆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")); 

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

+0

因爲,不像['HashMap'](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html),['ConcurrentHashMap'](HTTPS: //docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html)不實現['Cloneable'](https://docs.oracle.com/javase/8/文檔/ API /爪哇/郎/ Cloneable.html)。事實突出顯示,您的代碼**不會編譯**,即該方法不可用! – Andreas

+1

@Andreas:儘管有這個名字,但實現'Cloneable'並不意味着你支持'clone',並且支持'clone'不需要你實現'Cloneable'。 'Cloneable'實際上並沒有將'clone'作爲公共方法。這是「克隆」設計的奇怪缺陷之一。 – user2357112

+0

支持'clone'確實需要實現'Cloneable'接口@ user2357112。 「在未實現Cloneable接口的實例上調用Object的clone方法會導致引發異常CloneNotSupportedException。」 - https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html –

回答

5

AbstractMap上的clone()方法不適用於複製,它是一種內部方法,請注意受保護的關鍵字。

protected Object clone() throws CloneNotSupportedException { 

HashMap恰好有一個公共clone(),但這並不意味着你應該使用它,這是由Effective Java: Analysis of the clone() method

進一步討論更爲靈活的方式來創建集合的拷貝是通過拷貝構造函數。這些有創建任何其他地圖實施的優勢。

/** 
* Creates a new map with the same mappings as the given map. 
* 
* @param m the map 
*/ 
public ConcurrentHashMap(Map<? extends K, ? extends V> m) { 

例如,

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"));