Java 如何更新作为对象的HashMap的值?
如果该值是名为Hand的类Java 如何更新作为对象的HashMap的值?,java,hashmap,Java,Hashmap,如果该值是名为Hand的类 public class Hand implements Iterable<Card>{ protected List<Card> cards; ..... ..... } 或者我需要做什么 hashMap.get(i).cards.add(Card Object) hashMap.put(i, hashMap.get(i).cards.add(Card Object)) 假设Hand实例已经存在,您将希望检索该
public class Hand implements Iterable<Card>{
protected List<Card> cards;
.....
.....
}
或者我需要做什么
hashMap.get(i).cards.add(Card Object)
hashMap.put(i, hashMap.get(i).cards.add(Card Object))
假设
Hand
实例已经存在,您将希望检索该实例:
Hand hand = hashMap.get(i);
拥有该实例后,您希望访问其卡
列表并向其中添加另一张卡:
Card card = ...;
hand.cards.add(card); //consider using a getMethod to get the cards
或者在您自己的代码中:
hashMap.get(i).cards.add(card);
您不需要在hashmap中重新映射hand元素,因为您没有替换实际的
hand
对象,因此映射中对它的引用保持不变。您所要做的就是通过在手牌
的卡中添加一个项目来修改其属性之一。在手牌
类中为卡
使用getter,如
protected List<Card> getCards() {
return this.cards;
}
企图
hashMap.put(i, hashMap.get(i).getCards().add(new Card()))
正在尝试将从
add
返回的boolean
放在索引i
中,这不符合您的逻辑。您是否尝试了这两个选项以查看结果?添加(卡对象)
将无法编译。
hashMap.get(i).getCards().add(new Card())
hashMap.put(i, hashMap.get(i).getCards().add(new Card()))