Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何更新作为对象的HashMap的值?_Java_Hashmap - Fatal编程技术网

Java 如何更新作为对象的HashMap的值?

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实例已经存在,您将希望检索该

如果该值是名为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()))