[英]Adding to a Hashset inside a Hashmap
我正在嘗試將對象添加到Hashmap中的Hashset。
這里gamesAndTeams
是一個Hashmap,它包含一個Hashset。
我通過網絡查看了一些教程,但我正在嘗試的是不起作用。
難道我做錯了什么?
Match newmatch = new Match(dateOfGame, stad, guestTeam, hostTeam, hostGoals, guestGoals);
gamesAndTeams.put(key, gamesAndTeams.get(key).add(newmatch));
您必須首先檢查密鑰是否存在於HashMap
。 如果沒有,您應該創建值HashSet
並將其放在HashMap
:
if (gamesAndTeams.containsKey(key))
gamesAndTeams.get(key).add(newmatch);
else {
HashSet<Match> set = new HashSet<>();
gamesAndTeams.put(key,set);
set.add(newmatch);
}
要么
HashSet<Match> set = gamesAndTeams.get(key);
if (set == null) {
set = new HashSet<>();
gamesAndTeams.put(key,set);
}
set.add(newmatch);
是。
假設gamesAndTeams
已經有一個key
的條目,你只需要
gamesAndTeams.get(key).add(newmatch);
......你不需要在地圖中put
任何東西,除非它以前根本不在地圖中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.