11.2 List Class | 533
publicList()
// Instantiates an empty list object with room for 100 items
{
numItems = 0;
listItems = new String[100];
currentPos = 0;
}
The observers isFull,isEmpty, and lengthare very straightforward. Each is only one line
long, as is so often the case in methods within the object-oriented paradigm.
public booleanisFull()
// Returns true if no room to add a component; false otherwise
{
return(listItems.length == numItems);
}
public booleanisEmpty()
// Returns true if no components in the list; false otherwise
{
return(numItems == 0);
}
public intlength()
// Returns the number of components in the list
{
returnnumItems;
}
We have one more observer to implement: isThere. Because isThereis an instance method,
it has direct access to the items in the list. We just loop through the items in the list looking
for the one specified in the parameter list. The loop ends when we find the matching item
or have looked at all items in the list. Our loop expression has two conditions: The index is
within the list, and the corresponding list item is not equal to the one for which we are
searching. After exiting the loop, we return the assertion that the index is still within the list.
If this assertion is true, then the search item was found.
We can code this algorithm directly into Java, using the compareTomethod of String.
isThere
Set index to 0
whilemore to examine and item not found
Increment index
return(index is within the list)