简体   繁体   中英

Adding to a Hashset inside a Hashmap

I'm trying to add an object to a Hashset within a Hashmap.

Here gamesAndTeams is a Hashmap, and it contains a Hashset.

I've looked over some tutorials over the web but what I'm trying isn't working.
Am I doing something wrong?

Match newmatch = new Match(dateOfGame, stad, guestTeam, hostTeam, hostGoals, guestGoals);
gamesAndTeams.put(key, gamesAndTeams.get(key).add(newmatch));

You must first check if the key is present in the HashMap . If not, you should create the value HashSet and put it in the HashMap :

if (gamesAndTeams.containsKey(key))
    gamesAndTeams.get(key).add(newmatch);
else {
    HashSet<Match> set = new HashSet<>();
    gamesAndTeams.put(key,set);
    set.add(newmatch);
}

or

HashSet<Match> set = gamesAndTeams.get(key);
if (set == null) {
    set = new HashSet<>();
    gamesAndTeams.put(key,set);
}
set.add(newmatch);

Yes.

Assuming gamesAndTeams already has an entry for key , you just want

gamesAndTeams.get(key).add(newmatch);

...you don't need to put anything in the map unless it was previously not in the map at all.

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