2016-07-17 3 views
1

ConcurrentHashMap을 복제 할 수없는 이유는 무엇입니까? 내가 HashMap 대신 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")); 

, 그것을 작동합니다.

+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/). docs/api/java/lang/Cloneable.html). 사실 **에서 코드 **가 컴파일되지 않습니다 **, 즉 해당 메서드를 사용할 수 없음을 강조했습니다. – Andreas

+1

@ Andreas : 이름에도 불구하고 Cloneable을 구현한다고해서 clone을 지원한다는 의미는 아니며 clone을 지원할 때 Cloneable을 구현할 필요가 없습니다. 'Cloneable'은 실제로 public 메소드로'clone '을 가지고 있지 않습니다. '복제품'디자인의 이상한 결함 중 하나입니다. – user2357112

+0

'clone '을 지원하려면'cloneable' 인터페이스 인 @ user2357112를 구현해야합니다. "Cloneable 인터페이스를 구현하지 않는 인스턴스에서 Object의 복제 메서드를 호출하면 CloneNotSupportedException 예외가 throw됩니다." - https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html –

답변

5

AbstractMapclone() 메서드는 복사하기위한 것이 아니며 내부 메서드이므로 protected 키워드를 유의하십시오.

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) { 

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