简体   繁体   中英

Check if an object already exists with a specific property

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM