2017-03-08 26 views
-4

如果該值是一個叫做手如何更新作爲對象的HashMap的值?

public class Hand implements Iterable<Card>{ 
    protected List<Card> cards; 
    ..... 
    ..... 
} 

類和我的HashMap是

HashMap<Integer, Hand> hashMap; 

如果我想一個卡對象添加到Handcards的實例字段,做我需要做的

hashMap.get(i).cards.add(Card Object) 

或做我需要做的

hashMap.put(i, hashMap.get(i).cards.add(Card Object)) 
+1

您是否嘗試過兩種選擇來查看會發生什麼? –

+0

'add(Card Object)'不會編譯。 –

回答

2

假設Hand實例已經存在,你想檢索實例:

Hand hand = hashMap.get(i); 

一旦你的情況,你要訪問其cards名單,並加入另一張卡吧:

Card card = ...; 
hand.cards.add(card); //consider using a getMethod to get the cards 

或者在自己的代碼:

hashMap.get(i).cards.add(card); 

您不需要重新映射散列映射中的手形元素,因爲您並未替換實際的Hand對象,因此在映射中對其的引用保持不變。您所做的只是通過在Hands的卡片中添加物品來修改其屬性之一。

0

使用cards一個getter Hand類中像

protected List<Card> getCards() { 
    return this.cards; 
} 

,然後更新如下 -

hashMap.get(i).getCards().add(new Card()) 

試圖

hashMap.put(i, hashMap.get(i).getCards().add(new Card())) 

正試圖把從add返回的boolean放在索引i,而不是用你的邏輯工作。