gpt4 book ai didi

java - 如何从HashMap中获取玩家列表

转载 作者:行者123 更新时间:2023-12-02 04:34:35 24 4
gpt4 key购买 nike

我找到了一个针对 Java 初学者的任务。这是我必须实现的接口(interface)。我决定对 Players 使用 HashMap,但现在我注意到我必须返回一个 Player 数组,对吗?您能帮我理解如何在 getAllPlayers() 方法中做到这一点吗?谢谢

public class LeagueManager implements Manager{
Map<String, Player> players = new HashMap<String, Player>();
public void addPlayer(Player player) {
players.put(player.getNick(), player);
}

public void removePlayer(Player player) {
if (!players.isEmpty()) {
players.remove(player.getNick());
}
}

public Player getPlayer(String name) {
if (!players.isEmpty() && players.containsKey(name)) {
return (Player) players.get(name);
} else {
System.out.println("Error: there is no player with nick " + name);
return null;
}
}

public Player[] getAllPlayers() {
if (!players.isEmpty()) {
return null;
} else {
return null;
}
}


public void addPoints (String name, int points) {
if (players.containsKey(name)) {
Player pl = (Player) players.get(name);
pl.setPoints(points);
}
}}

最佳答案

您可以使用players.values().toArray 获取数组形式的值。

public Player[] getAllPlayers() {
Player[] result = new Player[players.size()];
return players.values().toArray(result);
}

关于java - 如何从HashMap中获取玩家列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31010086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com