this is the player class
package day6;
public class Player {
int playerId;
public Player(int playerId) {
super();
this.playerId = playerId;
}
public int getPlayerId() {
return playerId;
}
}
this is the position class
package day6;
public class Position {
private int positionNumber = 0;
public Position(int positionNumber) throws Exception {
super();
this.positionNumber = positionNumber;
}
public int getPositionNumber() {
return positionNumber;
}
}
this is the game class
package day6;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public class Game {
private int numberOfPlayers;
HashMap<Player, Position> hashMapForPositionOfPlayer = new HashMap<Player, Position>(numberOfPlayers);
@SuppressWarnings("unchecked")
public Game(int numberOfPlayers) throws Exception {
super();
this.numberOfPlayers = numberOfPlayers;
for (int i = 0; i <numberOfPlayers; i++) {
hashMapForPositionOfPlayer.put(new Player(i), new Position(0));
}
}
public void play() throws Exception {
Position currentPosition;
for (int i = 0; i < numberOfPlayers; i++) {
Player player = new Player(i);
currentPosition = hashMapForPositionOfPlayer.get(player);
int value = currentPosition.getPositionNumber();
}
}
}
I tried to run the program Game class and game.play() but it is showing null value to the 0th value of the hashmap.
it means currentPosition=null for hashmap of key value 0.
Help me..
Since you’re using
Playerinstances as keys of theHashMap, it should implementhashCode()andequals()consistently, so that twoPlayerinstances are considered to represent the same player when theirplayerId‘s are equal.Without implementing
equals()properly, the following snippet would return false:Also, given the nature of the
Mapimplementation you’ve chosen,HashMap, the check for existing keys in theMapwill be associated to theirhashCode, so it is necessary to also implementhashCodeto reflect that twoPlayerinstances are equal if theirplayerId‘s are.The following question might be useful to you: Understanding the workings of equals and hashCode in a HashMap.
Sample code: