我使用两个ConcurrentHashMaps来存储以下数据。我将使用以下作为示例
private Map<Player, FootballTeam> playerTeamMapping;
private Map<FootballTeam, League> teamLeagueMapping;
仅给出FootballTeam
对象,我需要能够检索Player
或League
个对象并执行一些操作
要考虑的案例:
如果没有Player
与FootballTeam
相关联但是
存在FootballTeam
条目,然后从中删除FootballTeam
条目
teamLeagueMapping
。
如果Player
(s)更改了FootballTeam
而FootballTeam
<
条目存在然后从中删除FootballTeam
条目
仅当没有其他播放器引用时才teamLeagueMapping
FootballTeam
到目前为止,我使用上面定义的两个地图,但出于学习目的,我被告知我需要定义自己的数据结构来解决这个问题。
我正在考虑创建一个由2个地图ThreeWayHashMap<Left, Middle, Right>
支持的通用类(Left = Player, Middle = FootballTeam, Right = League)
。这是最好的方法吗?我需要在删除时基本上保持三个地图同步,所以在删除条目时(我需要确保我在两者上执行这些操作)。
答案 0 :(得分:1)
您可以使用现有的类来表示映射。
League
应该Set<FootballTeam>
而FootballTeam
应该有Set<Player>
,而且League和FootballTeam都应该有实用方法来添加或删除团队中的玩家并添加或删除团队联赛。
public class League {
Set<FootballTeam> teams = new HashSet<FootballTeam>();
public void addPlayer(FootballTeam team, Player player) {
team.addPlayer(player);
teams.add(team);
}
public void removePlayer(FootballTeam team, Player player) {
team.removePlayer(player);
teams.remove(team);
}
public void movePlayer(FootballTeam from, FootballTeam to, Player player) {
from.movePlayerTo(to, player);
if (from.getPlayers().size() == 0 ) {
teams.remove(from);
}
teams.add(to);
}
}
public class FootballTeam {
private Set<Player> players = new HashSet<Player>();
public void addPlayer(Player player) {
player.setTeam(this);
players.add(player);
}
public void removePlayer(Player player) {
player.setTeam(null);
players.remove(player);
}
public void movePlayerTo(FootballTeam to, Player p) {
player.setTeam(to);
players.remove(p);
}
}