如何减少HashMap中的值?

时间:2015-03-31 23:29:49

标签: java hashmap decrement

所以我正在为我正在制作的棋盘游戏中的每位玩家提供playerIDnumwalls。 现在,当每个玩家使用一个墙壁时移除墙壁,每个人基本上都是共享墙壁。

所以我认为我应该hashmapplayerID为键,numwalls为值。

但我不知道在应该使用墙壁时如何减小键值。

我将展示一个有问题的代码。

public int getWallsRemaining(int i) {
    return numWalls;
}

public void lastMove(PlayerMove playerMove) {
    System.out.println("in lastMove... " + playerMove);
    /**
     * if piece moves, update its position
     */
    if(playerMove.isMove() == true){

        Integer player = playerMove.getPlayerId();

        Coordinate newLoc = new Coordinate(playerMove.getEndRow(), playerMove.getEndCol());
        playerHomes.put(player, newLoc);

    }
    /**
     * if a wall is placed, subtract the wall form the player who placed it
     * and subtract the appropriate neighbors.
     */
    if(playerMove.isMove() == false){
        numWalls-=1;
        removeNeighbor(playerMove.getStart(), playerMove.getEnd());

    }


}

这是我初始化所有内容的地方,walls是我正在尝试做的地图:

private Map<Coordinate, HashSet<Coordinate>> graph;

private int PlayerID;
private int numWalls;
private Map<Integer, Coordinate> playerHomes;
private Map<Integer, Integer> walls;



@Override
public void init(Logger logger, int playerID, int numWalls, Map<Integer, Coordinate> playerHomes) {


    this.PlayerID = playerID;
    this.walls = new HashMap<Integer, Integer>();
    this.numWalls = numWalls;
    this.playerHomes = playerHomes;
    this.graph = new HashMap<Coordinate, HashSet<Coordinate>>();
    walls.put(playerID,numWalls);

    for(int r = 0; r <= 10; r++){
        for(int c = 0; c <= 10; c++){
            HashSet<Coordinate> neighbors = new HashSet<Coordinate>();
                 if(r > 0){
                    neighbors.add(new Coordinate(r - 1, c));
                 }
                if(r < 8){
                     neighbors.add(new Coordinate(r + 1, c));
                 }
                if(c > 0){
                    neighbors.add(new Coordinate(r, c - 1));
                 }
                if(c < 8){
                    neighbors.add(new Coordinate(r, c + 1));
                 }
            graph.put((new Coordinate(r,c)), neighbors);
        }
    }
}

你可以在我的lastMove方法中看到我减去1的墙。这是我的问题。我希望将指定的playerID numwall递减1.我现在只为1个玩家工作。我需要这个才能为最多4个玩家工作。

3 个答案:

答案 0 :(得分:2)

HashMap只能包含对象(不是基元),因此您必须插入Integer作为映射值。

由于Integer是不可变类,因此无法直接修改该值,您需要通过丢弃旧值来替换它,例如:

HashMap<Player, Integer> walls = new HashMap<Player,Integer>();

int currentWalls = walls.get(player);
walls.put(player, currentWalls-1);

答案 1 :(得分:1)

我使用AtomicInteger来保存您的价值观。它是线程安全的,以防多个玩家同时进入墙壁。并且它比每次重新创建一个新的Integer更简单(如@Jack答案)

HashMap<Player, AtomicInteger> walls = new HashMap<Player,AtomicInteger>();

...

walls.get(player).decrementAndGet();

如果需要,您可以从decrementAndGet()调用中返回值以检索新的墙数。

答案 2 :(得分:0)

要更改使用键存储的值,您应删除旧值并添加新值。

那就是说,您是否考虑过创建一个Player类来封装playerId以及玩家拥有的墙数?它可能对你的计划更有效。