Java Reference
In-Depth Information
izer, an event model, and some internationalization tools. But this package also contains a set
of collection interfaces and implementations that, when properly understood and used, can
save a programmer a huge amount of time and effort.
The List interface allows us to add Player objects to the team, remove Players , and iterate
through the group of players. If we add a Player object to a list that is already full, the List
will automatically resize. We can control where in the list a Player object is added, or we can
just use the default and add a player to the end of the list. A List also allows the same Player
object to be inserted into the List multiple times; if we do that, removing a player will still
leave some copies of the Player object in the list, and iterating through the list will give us
multiple instances of that Player . In fact, the List acts a lot like an array of player objects, but
frees us from having to do much of the maintenance of the array (such as resizing or moving
entries around) when we want to insert an entry in a particular place. And that's the idea: the
collections are here to free us from writing code.
But the fact that we can insert the same Player object into a List multiple times and end up
with multiple occurrences of that Player object on the Team doesn't seem right. After all, the
same player can be on a team only once, at least at any one time. What we really want is for
the Team to contain some way of storing all of the Players on the team so that we are guaran-
teed that no Player can be inserted twice on the same Team (or remain after being removed).
We could do this by adding our own checks to the addPlayer() and removePlayer() meth-
ods. We could, for example, begin the addPlayer() method with a check to see whether the
Player being inserted was already in the List and simply return the answer. Even though this
should keep any duplicate Player objects out of the List , we will also add some code to our
removePlayer() method to ensure that multiple copies of any Player object will be removed
when that method is called. The resulting (first) implementation of a class that implements the
Team interface might look something like:
package org.oreilly.javaGoodParts.examples.impl;
import java.util.ArrayList;
import java.util.List;
import org.oreilly.javaGoodParts.examples.statistics.Player;
import org.oreilly.javaGoodParts.examples.statistics.Team;
* A first implementation of the Team interface, using
* an ArrayList as the backing store for the Players on
Search WWH ::

Custom Search