拯救团队成员的聪明方法
smart way to save team members
我想要一份包含团队成员的团队列表。
(我在 java 中编写示例代码,但解决方案不必使用 java。)
像这样:
class Member {
}
class Team {
ArrayList<Member> members;
}
ArrayList<Team> teams;
如果我想访问一个团队的所有团队成员,那将非常简单。
但是如果我想查看某个成员属于哪个团队怎么办? of?
我不想每次都遍历所有团队成员。
我可以把每个成员的团队都保存在成员的 class 里面,但是那不是很笨吗?
使用双向关联。您将需要额外的方法来确保数据保持一致。在示例中,我通过向 Team
添加 newMember
方法解决了这个问题,但也可以通过添加将设置团队并同时更新成员列表的设置器来解决。
class Member {
final Team team;
Member(Team team) {
this.team = team;
}
}
class Team {
ArrayList<Member> members;
public Member newMember() {
Member member = new Members(this);
members.add(member);
return member;
}
}
只需使用一个字符串类型的数组和一个 for 循环来打印出所有团队和团队成员。
String[][] teams = new String[2][4];//[numer of team][max. number of memebers per team + one]
teams[0][0] = "team1";
teams[0][1] = "team1Member1";
teams[0][2] = "team1Member2";
teams[0][3] = "team1Member3";
teams[1][0] = "team2";
teams[1][1] = "team2Member1";
teams[1][2] = "team2Member2";
teams[1][3] = "team2Member3";
//get all members of all teams
for(int i = 0; i < teams.length; i++){
System.out.println("team: " + teams[i][0]);
for(int j = 1; j < teams[0].length; j++){
System.out.println("\t" + teams[i][j]);
}
}
我想要一份包含团队成员的团队列表。
(我在 java 中编写示例代码,但解决方案不必使用 java。)
像这样:
class Member {
}
class Team {
ArrayList<Member> members;
}
ArrayList<Team> teams;
如果我想访问一个团队的所有团队成员,那将非常简单。
但是如果我想查看某个成员属于哪个团队怎么办? of?
我不想每次都遍历所有团队成员。
我可以把每个成员的团队都保存在成员的 class 里面,但是那不是很笨吗?
使用双向关联。您将需要额外的方法来确保数据保持一致。在示例中,我通过向 Team
添加 newMember
方法解决了这个问题,但也可以通过添加将设置团队并同时更新成员列表的设置器来解决。
class Member {
final Team team;
Member(Team team) {
this.team = team;
}
}
class Team {
ArrayList<Member> members;
public Member newMember() {
Member member = new Members(this);
members.add(member);
return member;
}
}
只需使用一个字符串类型的数组和一个 for 循环来打印出所有团队和团队成员。
String[][] teams = new String[2][4];//[numer of team][max. number of memebers per team + one]
teams[0][0] = "team1";
teams[0][1] = "team1Member1";
teams[0][2] = "team1Member2";
teams[0][3] = "team1Member3";
teams[1][0] = "team2";
teams[1][1] = "team2Member1";
teams[1][2] = "team2Member2";
teams[1][3] = "team2Member3";
//get all members of all teams
for(int i = 0; i < teams.length; i++){
System.out.println("team: " + teams[i][0]);
for(int j = 1; j < teams[0].length; j++){
System.out.println("\t" + teams[i][j]);
}
}