1

My program allows football coaches to be assigned to teams.

private String name;
private Team team;

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

How do I check if a 'Coach' object with a specific 'Team' already exists. I want to stop two coaches from being assigned to the same Team.

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);

I have spent hours reading similar questions but I haven't been able to get any of the code work. Any help would be appreciated, I'm pulling my hair out.

Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
Bailey280899
  • 151
  • 1
  • 1
  • 5

2 Answers2

0

You'll have to store your coaches in some kind of collection. Given the specific use case you stated, a Map<Team, Coach> seems appropriate:

Map<Team, Coach> coachesByTeam = new HashMap<>();
if (!coachesByTeam.containsKey(team)) {
    Coach coach = new Coach(name, team);
    coachesByTeam.put(team, coach);
}
OhleC
  • 2,821
  • 16
  • 29
  • I couldn't get this to work, when the user presses the 'Create' button which runs this code, it allows two coaches to be created for the same team. – Bailey280899 Dec 08 '18 at 22:47
  • The map needs to be created somewhere outside the button event handler function. Did you perhaps create it there? – OhleC Dec 08 '18 at 23:03
  • So the Map needs to be outside the button, and the if statement needs to be inside the button? – Bailey280899 Dec 08 '18 at 23:07
  • @Bailey280899 Correct. Otherwise, you will create a new empty map each time, and checking whether the team is in there makes no sense. – OhleC Dec 08 '18 at 23:12
  • Okay, that makes sense but when I move the Map outside the button click event handler, it's underlined in red and can't find the Map? – Bailey280899 Dec 08 '18 at 23:15
  • @Bailey280899 Giving more specific advice is hard when we don't know how you structured the rest of your code. If this data structure (the association of teams with coaches) is central to your application as a whole, you should probably create the map somewhere central and maybe keep a reference to it as a field in the class that also contains your button. – OhleC Dec 08 '18 at 23:37
0

You need to use Set for this, for example

  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);
   }
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59