如何递减 HashMap 中的值?

How to decrement a value in a HashMap?

所以我在我制作的棋盘游戏中为每个玩家设置了 playerIDnumwalls。 现在一人一墙拆墙,基本上大家共享墙

所以我想我应该做一个 hashmap 来保存 playerID 作为键和 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 方法中看到我将 walls 减 1。这是我的问题。我想将指定的 playerID numwall 减 1。我现在所拥有的仅适用于 1 个玩家。我需要它最多支持 4 个玩家。

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

因为 Integer 是不可变的 class 你不能直接修改这个值,你需要通过丢弃旧值来替换它,比如:

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

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

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

也就是说,您是否考虑过创建一个Player class 来封装playerId 和玩家拥有的墙数?它可能更适合您的计划。

我会使用 AtomicInteger 来保存您的值。它是线程安全的,以防多个玩家同时 运行 撞墙。而且它比每次都重新创建一个新的 Integer 更简单(如@Jack 的回答)

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

...

walls.get(player).decrementAndGet();

如果需要,您可以 return 来自 decrementAndGet() 调用的值来检索新的墙数。