Java Reference
In-Depth Information
This means that when we declare a
Set
of a particular type, that type will be used to replace all
of the instances of the type variable
E
in the definition. So by returning a
Set<Player>
from
getRoster()
, we assure that only a
Player
object can be added to the
Set
, and the
Iterator
that is returned from the
iterator()
method on that
Set
will give us only
Player
objects.
We don't have to cast the result of using the iterator, and the compiler can check all of these
guarantees.
To see how this works in practice, let's go back to our baseball statistics package. We start by
changing the
Team
interface so that the return value of
getRoster()
uses generics, adding a
type parameter to the return type:
package org.oreilly.javaGoodParts.examples.statistics;
import java.util.Set;
/**
* The <code>Team</code> interface, which defines
* the notion of a team for our statistics package. A
* team is, at first incarnation, simply a collection of
* players. All teams have a name.
*/
public interface Team {
/**
* Return a <code>String</code> that is the name of
* this team.
*/
String getName();
/**
* Return the players that are on this
* team. The set returned is a set of player
* objects.
*/
Set<Player> getRoster();
/**
* Add a player to the team.
*/
void addPlayer(Player toAdd);
/**
* Remove a player from the team.