Setter 方法在彼此的类中设置字段
我有两个类,玩家类和团队类。一个球员有一个 team 字段,一个球队有一个playerList 字段,包含该球队的球员。当玩家加入队伍时,玩家的队伍字段应设置为该队伍,并且队伍的playerList应添加加入的玩家对象。这是我到目前为止所拥有的,但这不是非常递归吗?我该如何解决这个问题?下面提供了示例代码。
public class Team {
private ArrayList<Player> playerList;
public void addPlayer(Player player){
playerList.add(player);
player.joinTeam(this);
}
}
public class Player {
private Team team;
public void joinTeam(Team team) {
this.team = team;
team.addPlayer(this)
}
}
I have two classes, Player and Team. A player has a team field, and a team has a playerList field, containing the players on that team. When a player joins a team, the player's team field should be set to that team, and the team's playerList should add the player object joining. This is what I have so far, but is this not very recursive? How can I solve this problem? Example code is provided below.
public class Team {
private ArrayList<Player> playerList;
public void addPlayer(Player player){
playerList.add(player);
player.joinTeam(this);
}
}
public class Player {
private Team team;
public void joinTeam(Team team) {
this.team = team;
team.addPlayer(this)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原则上,对于特定类型的操作,您应该只拥有一个函数。如果您想将玩家添加到团队中,类似的东西
会更适合您的任务。您只需调用一个方法 (
addPlayer
),您希望发生的两项操作就会发生。In principle, you should only really have one function for a specific type of action. If you want to add a Player to a Team, something like
would be better suited for your task. You only call one method (
addPlayer
) and both actions you want to have happen, will happen.那么,为了使您的代码正常工作,您应该从方法
joinTeam()
中删除team.addPlayer(this)
。但现在您只是为属性设置一个值,因此它应该是setTeam()
。Well, to make your code work, you should just remove
team.addPlayer(this)
from the methodjoinTeam()
. But now you are just setting a value to your attribute, so it should be asetTeam()
.