Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^528) | Array-Based Lists
We have several choices in how we handle this possibly dangerous situation. The list can
throw an exception, reset the current position when inserting or deleting, or disallow trans-
former operations while an iteration is taking place. We choose the latter option here by
way of an assumption in the documentation. In case the user wants to restart an iteration,
let’s provide a resetListmethod that reinitializes the current position.
public voidresetList()
// The current position is reset
publicString getNextItem()
// Assumption: No transformers are called during the iteration
Before moving on to the implementation phase, let’s consider how we might use
getNextItem. Suppose the client code wants to print out the items in the list. The client ap-
plication cannot directly access the list items, but it can use getNextItemto iterate through
the list. The following code fragment prints the string values in list:
String next;
for (int index = 1; index <= list.length(); index++)
{
next = list.getNextItem(); // Get an item
System.out.println(next + " is still in the list");
}
Now is also the time to review the CRC card and see whether we need to add any re-
sponsibilities. For example, do we need to provide an equalstest? If we want to perform a deep
comparison of two lists, we must provide equals; however, comparing lists is not a particu-
larly useful operation, and we can provide the client with the tools needed to write a com-
parison operation if necessary. In fact, here is the algorithm to compare two lists. It determines
whether the lengths match; if they do, it iterates through the lists checking whether corre-
sponding items are the same.
isDuplicate
iflengths are not the same
returnfalse
else
Set counter to 1
Set same to true
Set limit to length of first list
whilethey are still the same AND counter is less than or equal to limit
Set next1 to next item in the first list
Set next2 to next item in the second list
Set same to result of seeing if next1.compareTo(next2) is 0
Increment counter
returnsame

Free download pdf