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

时间:2018-12-08 22:15:22

标签: java object

我的程序允许将足球教练分配给球队。

private String name;
private Team team;

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

如何检查具有特定'Coach'的{​​{1}}对象是否已存在。我想阻止两名教练被分配到同一支球队。

'Team'

我已经花了数小时阅读类似的问题,但是我无法获得任何代码。任何帮助将不胜感激,我正在拔头发。

2 个答案:

答案 0 :(得分:0)

您必须将您的教练存储在某种集合中。给定您指定的特定用例,Map<Team, Coach>似乎合适:

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

答案 1 :(得分:0)

例如,您需要使用Set

  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);
   }
相关问题