Java Reference
In-Depth Information
Note that we have used the ArrayList class to store the Player objects on the Team . An Ar-
rayList is an implementation of the List interface, using an array as the backing store. It
handles all of the issues around using an array, such as resizing, shuffling, and constructing an
iterator over the array. We could have done this ourselves, but using the existing code means
that we don't have to write the code ourselves. Further, the existing code is tested, debugged,
and probably runs at least as fast as the code we would have written (and, very likely, runs
But there is a better way. Although we have collected the Player objects using a List , we
really don't want the semantics of a List . We would really like a collection that allows a
Player to be in the collection only once. And there is such an interface and implementation in
the collection classes: the Set . Looking at the javadoc, we can see that a Set is a collection in
which no element can occur multiple times. Unlike a List , a Set does not guarantee the order
of the elements stored in it when you iterate over the Set . But we aren't going to depend on
the order of our Player objects in such an iteration, so the Set seems to fit the bill nicely.
The first thing we need to do is change our Team interface, removing the List that is returned
from the getPlayerList() method and returning a Set instead. While we are doing that, we
will change the name of the method to better reflect what is being returned. The result will
look something like:
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
Search WWH ::

Custom Search