通过索引查找对象,HashMaps还是循环遍历ArrayList?哪个最快? (Java)的

时间:2015-11-03 15:18:11

标签: java optimization arraylist indexing hashmap

目前在我的游戏中,如果我想通过他们唯一的ID找到一个玩家,我会做这样的事情:

public Player getPlayerByID (int id) {
    for (Player player : playerList) {
        if (player.getId() == id)
            return player;
    }
    return null;
}

使用java HashMap会更快地为播放器编制索引吗?使用这样的东西:

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

//Some method to fill hash map with players...

//Get player method
public Player getPlayerByID (int id) {
    playerMap.get(id);
}

0 个答案:

没有答案