The Methods getIndexOf and contains
In this lesson, we will define the methods getIndexOf and contains so that they do not duplicate the search for a given string.
We'll cover the following...
Having just defined the private method removeEntry in the previous lesson, we now need to locate the string to remove from the bag so we can pass its index to removeEntry. That is, we must define the private method getIndexOf.
Locating the string to remove: The dilemma
We want the private method getIndexOf to search the array of bag entries for a given string and to return the string’s index if it is found. But the method contains already does the same search. Unfortunately, contains returns true or false; it does not return the index of the string it locates in the array. Thus, getIndexOf cannot simply call contains.
📝 Design decision: Should the method
containsreturn the index of a located entry?Should we change the definition of
containsso that it returns an index instead of a Boolean value?No!
- As a public method,
containsshould not provide a client with such implementation details.- The client should not expect that a bag’s entries are in an array, since they are in no particular order.
Instead of changing the specifications for
contains, we will follow our original plan to
- Define a private method
getIndexOfto search for a string and return its index.- Revise the definition of
containsto callgetIndexOfso that we can write the code for the search only once.
The definition of getIndexOf
We want getIndexOf to perform the search that is now in our original definition of contains. Let’s recall the loop in contains that performs the search:
boolean found = false;
for (int index = 0; !found && (index < numberOfStrings); index++)
{
if (aString.equals(bag[index]))
{
found = true;
} // End if
} // End for
After this loop ends, found indicates whether the search was successful.
The structure of the loop is suitable for the method getIndexOf, but we must save the value of index when the string is found. We want getIndexOf to return this index instead of a Boolean value. To revise the loop, we define an
integer variable, where, to record the value of index when aString equals bag[index]. Thus, the loop looks like this:
int where = -1; // ADDED
boolean found = false;
for (int index = 0; !found && (index < numberOfStrings); index++)
{
if (aString.equals(bag[index]))
{
found = true;
where = index; // ADDED
} // End if
} // End for
// Assertion: If where > -1, aString equals bag[where];
// otherwise, aString is not in the array.
With this loop as its body, the method getIndexOf returns the value of where. Notice that we initialize
where to –1, which is the value to return if aString is not found.