Nir Tzezana
Nir Tzezana

Reputation: 2342

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));

Upvotes: 1

Views: 1857

Answers (2)

Eran
Eran

Reputation: 394146

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);

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198481

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.

Upvotes: 1

Related Questions