C
C
Cyrus Smith2015-06-23 20:41:48
Java
Cyrus Smith, 2015-06-23 20:41:48

How to return a list of players from a hashMap?

Hello everyone,
Yes, so I have a LeagueManager class. It has a "map" of players HashMap. The key is the player's nickname (String), the value is the player himself (Player).
The question is written in the topic, but I will duplicate it: How to return a list of players from a hashMap? (the problem is in the getAllPlayers() method)

import java.util.HashMap;
import java.util.Map;
public class LeagueManager implements Manager{
Map players = new HashMap();
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;
}
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cyrus Smith, 2015-06-23
@CSmith

Heroes were also found on the foreign resource and offered this option:

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

Here is my worker. But thank you all for stopping by!
Z.Y. As I understand it, type change is avoided here, thereby cutting off the error that fell out to me when using the solution from EugeneP2

E
Evhen, 2015-06-23
@EugeneP2

public Player[] getAllPlayers() {
      return  (Player[])players.values().toArray();
}

Interface Map
And don't forget about generics

B
bromzh, 2015-06-24
@bromzh

Who are generics for?

Map<String, Player> players = new HashMap<>();
...
public List<Player> getAllPlayers() {
return players.values();
}

Write normal code. Learn collections and generics in Java, this is the basis.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question