我找到了Java初学者的任务。这是我必须实现的接口。 我决定使用HashMap for Players,但现在我注意到我必须返回一个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);
}
}}
答案 0 :(得分:2)
您可以使用players.values()。toArray将值作为数组获取。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// included to allow fragment to receive onActivityResult
}
答案 1 :(得分:0)
使用以下内容:
public class LeagueManager {
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 players.values().toArray(new Player[players.size()]);
} else {
return null;
}
}
public void addPoints (String name, int points) {
if (players.containsKey(name)) {
Player pl = (Player) players.get(name);
pl.setPoints(points);
}
}
}
它返回一个与hashMap大小相关的玩家数组。