防止多次添加hashmap键条目?

时间:2014-10-12 13:19:26

标签: java hashmap bukkit

我正在使用Bukkit为Minecraft创建一个迷你游戏引擎,但似乎在向游戏添加玩家时存在问题。成功添加玩家后,他有能力再次加入,因此不止一次参与。

这真的很奇怪,因为在我的if语句中,我会检查参与者的HashMap是否包含播放器密钥。如果确实如此,则不应允许他再次加入游戏。

这是我的方法。

public void addPlayer(Client client) {

    // Checks if the game is waiting, and the slots are sufficient.

    if (game.isWaiting() && !game.isFull() && !game.getClients().containsKey(client)) {

        Random random = new Random();

        int teamChance = random.nextInt(game.getTeams().size());

        // Adding the player to the match and assigning the default kit.

        game.getClients().put(client, game.getDefaultKit());

        // Adding the player to a team.

        game.getTeams().get(teamChance).add(client);

        // Checking if the slots are now maximum, prepare the game.

        if (game.isFull()) {
            prepareGame();
        }

        // If the player was added.

        if (game.getClients().containsKey(client))
        {
            Main.log("Added " + client.getName() + " (" + game.getCurrentSlots() + "/" + game.getSlots() + ")" + " to " + game.getType().getName() + " (" + game.getWorld().getName() + ").", Level.INFO);

            game.broadcast("Join", client.getName() + " (" + game.getCurrentSlots() + "/" + game.getSlots() + ")");

            client.getPlayer().teleport(game.getWorld().getSpawnLocation());

            client.reset();

            // Adding lobby items to the player's inventory.

            new LobbyManager(game);
        }
    }

来自Game班。

private HashMap<Client, Kit> clients;

// ...

public HashMap<Client, Kit> getClients() {
    return this.clients;
}

如何修改此方法以防止玩家多次加入游戏?

非常感谢您的帮助。


客户:http://pastebin.com/Fmgc0T3C

1 个答案:

答案 0 :(得分:1)

如果两个线程可能正在添加相同的客户端,则应lock将操作添加到游戏中的操作equals() and hashCode()!当您每次玩家想要加入时创建新的客户端对象时,您必须覆盖{{3}},因为当您在不同客户端对象中比较同一客户端时,conainsKey将返回false。