I have a relatively simple database containing a Player
table (a single field username
) and a Game
(a single field date
) one. As a Player
can take part in multiple Game
and a Game
can be played by multiple Player
, I use a many-to-many
relationship where an extra column score
is added to the joined table to store the score of a Player
in a Game
.
In my Java code, I have obviously a Player
class with field username
and a Game
one with field date
. However, I do not know if I should create a third class for the join table or if I should add a List<Player>
attribute within the Game
class along with a list of List<Integer>
to store the score.
EDIT: Example
Player
table:
player_id player_name
1 Bob
2 Lea
3 John
Game
table:
game_id game_date
1 20/08/2017
2 19/08/2017
Joined
table:
game_id player_id score
1 1 50
1 2 35
2 1 50
2 3 29
I would not create a separate class for the joined
table. I would go with a Map<Player, Integer>
in the Game
class to hold the players in the game and their respective scores.
Something like so (simple, no error checks):
class Game {
Map<Player, Integer> playerScores = new HashMap<>();
void addPlayer(Player p) {
playerScores.put(p, 0);
}
void incrementScore(Player p, int increment) {
int newScore = getScore(p) + increment;
playerScores.put(p, newScore);
}
int getScore(Player p) {
return playerScores.get(p);
}
// etc...
}
Why you don't add score attribute to Player class?
1 player probably can't be in 2 games at same time, right?
Reason why I say this is because you would then need only one list, with your approach you end up with 2 lists which are not directly connected. Yes I know that you will place player and his score at same index but this complicates things a lot.
Situation that I can think of just now is showing scoreboard, in other to show which player has highest score you need to sort it, how would you do it with your 2 lists?
In some complicated way for sure, you would first need to connect first and second list in some structure like map or something, probably you would need to use TreeMap<Integer, List<Players>>
, where Integer would be the score and for each score you would need List of players because 2 or more players could have same score.
By having score in your Player class you avoid this complications and make accessing score of each player very easy, once they leave game you simply take score, save in database and set back to 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.