Reputation: 925
I'm using two ConcurrentHashMaps to store the following data. I'll use the following as an example
private Map<Player, FootballTeam> playerTeamMapping;
private Map<FootballTeam, League> teamLeagueMapping;
Given just the FootballTeam
object, I need to be able to retrieve either the Player
or League
objects and perform some operations
Cases to consider:
If there are no Player
's associated to a FootballTeam
but a
FootballTeam
entry exists then remove the FootballTeam
entry from
teamLeagueMapping
.
If a Player
(s) changes their FootballTeam
but a FootballTeam
entry exists then remove the FootballTeam
entry from
teamLeagueMapping
only if no other Player is referencing the
FootballTeam
So far i'm using both maps defined above but for learning purposes, i've been told I will need to define my own data structure to solve this problem.
I'm thinking of creating of creating a generic class ThreeWayHashMap<Left, Middle, Right>
that is backed by the 2 maps (Left = Player, Middle = FootballTeam, Right = League)
. Is this the best approach to take? I need to basically keep three maps in sync when deleting so when removing entries (i'll need to make sure I perform these operations on both).
Upvotes: 1
Views: 153
Reputation: 5837
You can use your existing classes to represent the mapping.
League
should have Set<FootballTeam>
and FootballTeam
should have Set<Player>
and both League and FootballTeam should have utility methods to add or remove a player from the team and add or remove a team from league.
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);
}
}
Upvotes: 1