gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:30 24 4
gpt4 key购买 nike

我的计划允许将足球教练分配到球队。

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

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

最佳答案

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

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

关于java - 检查具有特定属性的对象是否已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com