Java Reference
In-Depth Information
Note that since our methods
addPlayer()
and
removePlayer()
only use methods on a
Set
,
we could have declared our private
players
variable simply as a
Set
rather than as a
HashSet
.
This would show that we depend only on the interface for a
Set
rather than on a particular im-
plementation of the
Set
. However, we still need to create a concrete instance of the
Set
some-
where. We could have some kind of factory method, perhaps controlled by some property, that
would determine at runtime what particular instantiation of the
Set
interface we would use.
But for the purposes of this example, we will tie the implementation of our
Player
interface
to an implementation of the
Set
interface, and create the
HashSet
directly in our
PlayerImpl
class.
Also note that what is returned from the method
getRoster()
is not a reference to the private
players
field, but a new
HashSet
that is initialized with the contents of that private field. This
ensures that no one can manipulate the contents of the
TeamImpl
object's copy of the roster.
This approach, which tries to return copies of private data rather than references to that private
data, is generally a good idea. Since Java has garbage collection, we don't even have to worry
about this creating a memory leak. Although there are some performance implications, they
are generally small and worth the added guarantees of correctness.
To use the objects in a collection like a
Set
, we can get an
Iterator
. An
Iterator
is a special
object that has a very simple interface. In its basic form, an
Iterator
contains only the meth-
ods
hasNext()
,
next()
, and
remove()
. But since most of what we want to do is go through
the objects in a collection (and know when we are done with that), these suffice.
For example, suppose we wanted to add a method to our
Formatter
object that would print
out the roster for a team. We would like to print out the name of the
Team
, and then print out
the names of the players on that team below, one per line, properly indented. To do this, we
would add the method:
public static void FormatRoster(Team toFormat){
Player p;
System.out.println(toFormat.getName());
Iterator e = toFormat.getRoster().iterator();
while (e.hasNext()){
p = (Player)e.next();
System.out.println("\t" + p.getName());
}
}