如何将2个数组列表放入一个哈希图中?

时间:2020-04-17 09:17:11

标签: java minecraft bukkit

因此,我正在制作一个插件,我想将(两个不同团队中的两个)ArrayList放到一个Hashmap中,这样我就可以用这种方法来获得两个团队:

public static Teams getTeam(Player player) {

    if (!hasTeam(player))
        return null;
    return zombiesTeam.get(player) && survivorsTeam.get(player);

}

这是我想要的两个ArrayList和一个Hashmap

public static HashMap<zombiesTeam, survivorsTeam> playerTeams = new HashMap<zombiesTeam, survivorsTeam>(); 
public static ArrayList<Player> zombiesTeam = new ArrayList<Player>();
public static ArrayList<Player> survivorsTeam = new ArrayList<Player>();

P.S。我知道此代码不正确

请询问我其他进一步的信息

谢谢。

2 个答案:

答案 0 :(得分:0)

您应该执行以下操作:

public static HashMap<String, ArrayList<Player>> playerTeams = new HashMap<>();

playerTeams.put("zombies", zombiesTeam);
playerTeams.put("survivors", survivorsTeam );

答案 1 :(得分:0)

如果您想用哈希图表示从团队名称到团队成员列表的所有“团队”,我建议这样做:

// In the same class where zombiesTeam and survivorsTeam are declared
public static Map<String, List<Player>> getTeamsByName() {
  Map<String, List<Player>> teamsByName = new HashMap<>();
  teamsByName.put("zombiesTeam", zombiesTeam);
  teamsByName.put("survivors", survivorsTeam);
  return teamsByName;
}

但是,请确保您需要使用静态字段和方法。您的模型不建议这样做。

例如,您宁愿声明一个Team类和一个Player类。由于您已经拥有Player类,因此我将如何制作Team类:

public class Team {
  private String name;
  private Set<Player> teamMembers = new HashSet<>();

  public Team(String name) {
    this.name = name;
  }

  public String getName() {
   return this.teamName;
  }

  public Set<Player> getTeamMembers() {
    return this.teamMembers;
  }

  public addPlayer(Player player) {
   this.teamMembers.add(player);
  }

  public removePlayer(Player player) {
   this.teamMembers.remove(player);
  }

  public reset() {
   this.teamMembers.clear();
  }
}

对于HashSet和HashMap,请务必覆盖equals和hashcode以使其正常工作。有关此处的更多信息:https://www.geeksforgeeks.org/equals-hashcode-methods-java/