Java Reference
In-Depth Information
Aside: Thinking positively
Unlike the method contains , the method getIndexOf uses the boolean variable found only to
control the loop and not as a return value. Thus, we can modify the logic somewhat to avoid the
use of the not operator ! .
Let's use a variable stillLooking instead of found and initialize it to true. Then we can
replace the boolean expression !found with stillLooking , as you can see in the following defi-
nition of the method getIndexOf :
// Locates a given entry within the array bag.
// Returns the index of the entry, if located, or -1 otherwise.
private int getIndexOf(T anEntry)
{
int where = -1;
boolean stillLooking = true ;
for ( int index = 0; stillLooking && (index < numberOfEntries); index++)
{
if (anEntry.equals(bag[index]))
{
stillLooking = false ;
where = index;
} // end if
} // end for
return where;
} // end getIndexOf
If anEntry is found within the array, stillLooking is set to false to end the loop. Some programmers
prefer to think positively, as in this revision, while others find !found to be perfectly clear.
2.29
A revised definition for the method contains . Having completed the definitions of remove and
the private methods they call, we realize that the method contains can call the private method
getIndexOf , resulting in a simpler definition than the one given in Segment 2.18. Recall that the
expression getIndexOf(anEntry) returns an integer between 0 and numberOfEntries - 1 if
anEntry is in the bag, or - 1 otherwise. That is, getIndexOf(anEntry) is greater than - 1 if anEntry
is in the bag. Thus, we can define contains as follows:
/** Tests whether this bag contains a given entry.
@param anEntry the entry to locate
@return true if the bag contains anEntry, or false otherwise */
public boolean contains(T anEntry)
{
return getIndexOf(anEntry) > -1;
} // end contains
Since we have changed the definition of contains , we should test it again. By doing so, we are
also testing the private method getIndexOf .
Note: Both the method contains and the second remove method must perform similar searches
for an entry. By isolating the search in a private method that both contains and remove can call, we
make our code easier to debug and to maintain. This strategy is the same one we used when we
defined the removal operation in the private method removeEntry that both remove methods call.
 
Search WWH ::




Custom Search