简体   繁体   中英

How update a value of a HashMap that is an object?

If the value is a class called Hand

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

and my HashMap is

HashMap<Integer, Hand> hashMap;

If I want to add a Card object to the instance field of Hand ie cards , do I need to do

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

or do I need to do

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

Assuming the Hand instance already exists, you would want to retrieve the instance:

Hand hand = hashMap.get(i);

Once you have the instance, you want to access its cards list and add another card to it:

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

Or in your own code:

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

You don't need to remap the hand element in the hashmap because you aren't replacing the actual Hand object, so the reference to it in the map remains the same. All you are doing is modifying one of its properties by adding an item in the Hands 's cards.

Use a getter for cards within Hand class like

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

and then update as follows -

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

Attempting

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

is trying to put a boolean returned from add at index i instead and wouldn't work good with your logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM