Java Reference
In-Depth Information
* @return The {@link Player} object for the player with the indicated
* playerId, or {@code null} if there is no player on the team with
* that id.
*/
Player getPlayer(UUID playerId);
}
Now we need to implement the new getPlayer() methods. Rather than iterate through the
Set of Player objects that we currently have in our TeamImpl , we will add a couple of new
fields that are collections themselves. What we want are ways of mapping from keys to Play-
er objects, where our keys will be either the ID of a Player or the name of the Player . This
is the functionality that is provided by the Map interface in the collections, so we will want
something that implements that interface. We will use the HashMap .
The mapping from IDs to Player objects is straightforward, since we know that the ID is
unique for each Player object. We simply declare a new member field that is a HashMap from
UUID objects to Player objects. This does require that we specify two type parameters, but
the resulting declaration looks something like:
private HashMap<UUID, Player> byIds;
Since names might not be unique, the declaration of the map from String objects to a Set of
Player objects is slightly more complex, looking like:
private HashMap<String, Set<Player>> byName;
Implementing our new getPlayer() methods is easy with these maps in the TeamImpl ob-
jects; we just take the ID or name supplied and return whatever is in the corresponding
HashMap . We do have to change the implementation of our addPlayer() and removePlay-
er() methods to update the new structures, but the only real complexity there is finding out
whether there is a Player with the same name already in the byName map and, if so, adding to
the existing Set rather than creating a new Set . The resulting implementation looks like:
package org.oreilly.javaGoodParts.examples.impl;
import java.util.HashMap;
import java.util.HashSet;
Search WWH ::




Custom Search