在JAVA中,我有一个HashMap,其中“ Player”对象作为键,而“ ArrayList”作为值。它用于存储每个玩家的对手。指向哈希图的变量称为playerOpponents。

现在,我想向某个玩家添加对手。是否需要像方法1一样在编辑后将列表放入地图中?

方法1:

private void addOpponent(Player p, Player opponent)
{
    ArrayList<Player> allOpponents = playerOpponents.get(p);
    allOpponents.add(opponent);
    playerOpponents.put(p,allOpponents);
}


方法2:

private void addOpponent(Player p, Player opponent)
{
    ArrayList<Player> allOpponents = playerOpponents.get(p);
    allOpponents.add(opponent);
}

最佳答案

不需要每次都放入列表引用。只需输入null检查。

private void addOpponent(Player p, Player opponent){
    List<Player> allOpponents = playerOpponents.get(p);
    if(playerOpponents.get(p)==null){
         allOpponents = new ArrayList<>();
         allOpponents.add(opponent);
         playerOpponents.put(p,allOpponents);
    }else
       allOpponents.add(opponent);
}

10-07 16:49