首页 文章

检查具有特定属性的对象是否已存在

提问于
浏览
1

我的计划允许将足球教练分配给球队 .

private String name;
private Team team;

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

如何检查具有特定 'Team''Coach' 对象是否已存在 . 我想阻止两名教练被分配到同一支队伍 .

String name = nameField.getText();
Team team = (Team) teamComboBox.getSelectedItem();

// I only want this to run, if the team doesn't already have a coach
Coach coach = new Coach(name, team);

我花了几个小时阅读类似的问题,但我无法获得任何代码工作 . 任何帮助将不胜感激,我正在拉我的头发 .

3 回答

  • 0

    您需要告诉Java如何识别相同的对象,并且需要覆盖方法equals . 如果需要将哈希代码存储在HashMap或HashSet中,您可能还需要覆盖哈希代码 .

  • 0

    例如,您需要使用Set for this

    Set<Team> teamsWithCoach = new HashSet<Team>();
      ...
      String name = nameField.getText();
      Team team = (Team) teamComboBox.getSelectedItem();
    
       if( !teamsWithCoach.contains(team) ) {
           Coach coach = new Coach(name, team); 
           teamsWithCoach.add(team);
       }
    
  • 0

    你必须将你的教练存放在某种集合中 . 鉴于您所说的具体用例, Map<Team, Coach> 似乎是合适的:

    Map<Team, Coach> coachesByTeam = new HashMap<>();
    if (!coachesByTeam.containsKey(team)) {
        Coach coach = new Coach(name, team);
        coachesByTeam.put(team, coach);
    }
    

相关问题