Java Reference
In-Depth Information
*/
public Set<Player> getRoster() {
return players;
}
/**
* Add a player to the team.
*/
public void addPlayer(Player toAdd) {
players.add(toAdd);
}
/**
* Remove a player from the team.
*/
public void removePlayer(Player toRemove) {
players.remove(toRemove);
}
}
Now we can change the method that prints out the roster for a team, simplifying it consider-
ably. We no longer need to check to see that the objects returned from the Set obtained by
calling getRoster() are players, since that has been ensured by the parameterized versions
of the collections that we are using. We also don't have to do the casting to the Player type.
So now our FormatRoster() method can look like:
public static void FormatRoster(Team toFormat){
System.out.println(toFormat.getName());
Iterator<Player> e = toFormat.getRoster().iterator();
while (e.hasNext()){
System.out.println("\t" + e.next().getName());
}
}
In fact, we can simplify this code even more. The Java language now has a special type of for
loop, just for iteration over collections. Instead of the code just shown, we could get the same
results with:
public static void FormatRoster(Team toFormat){
System.out.println(toFormat.getName());
for (Player i : toFormat.getRoster()){
Search WWH ::




Custom Search