【问题标题】:Adding to a Hashset inside a Hashmap添加到 Hashmap 内的 Hashset
【发布时间】:2015-05-27 18:43:58
【问题描述】:

我正在尝试将对象添加到 Hashmap 中的 Hashset。

这里gamesAndTeams是一个Hashmap,它包含一个Hashset。

我在网上查看了一些教程,但我尝试的方法不起作用。
我做错了吗?

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

【问题讨论】:

  • 哪个是你的HashSet,哪个是你的HashMap
  • 您也应该添加观察到的和期望的输出。
  • 这个问题已经得到解答,但对于未来研究这个问题的人来说:gamesAndTeams 是一个 Hashmap,它包含一个 Hashset。

标签: java hashmap hashset


【解决方案1】:

您必须首先检查密钥是否存在于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);

【讨论】:

  • @LouisWasserman 谢谢。我从第一个 sn-p 复制 HashSet&lt;Match&gt; 时忘记删除它。
【解决方案2】:

是的。

假设gamesAndTeams 已经有一个key 的条目,你只想

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

...您不需要 put 地图中的任何内容,除非它以前根本不在地图中。

【讨论】:

    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2018-11-16
    相关资源
    最近更新 更多