2016-04-25 33 views
0
HashMap<String, Set<Myclass>> mapNew = new HashMap<String, Set<Myclass>>(); 

for (Map.Entry<String, Set<Myclass>> entry : mapOrig.entrySet()) { 
     mapNew.put(entry.getKey(), entry.getValue().clone()); 
    } 

.clone()不在這裏工作了 我想改變,在新的項目,但保留原始不受影響。如何使用一組類克隆的HashMap中的Java

回答

0

我想出了這個,但它似乎尷尬。有沒有更好的辦法?

for (Map.Entry<String, Set<Myclass>> entry : mapOrig.entrySet()) { 
     Set<Myclass> objs = entry.getValue(); 
     Set<Myclass> objsCloned = new HashSet<Myclass>(); 
     for(Myclass obj : objs) 
     { 
      objsCloned.add(obj.clone()); 
     } 

     mapNew.put(entry.getKey(), objsCloned); 
    } 
+1

是的,這是尷尬的objsCloned爲null,並且從來沒有得到一組合適的實例,因此它不能工作:) – Walfrat

+0

我改變objsCloned到正確的初始化,怎麼啦? – user2568374

+0

我不知道如何工作映射和設置克隆功能,但我想這樣很好,只要你總是使用hashet,這是一個適當的克隆。 – Walfrat