Java Reference
In-Depth Information
The definition of getIndexOf will be like the definition of contains , which we recall here:
public boolean contains(T anEntry)
{
boolean found = false ;
for ( int index = 0; !found && (index < numberOfEntries); index++)
{
if (anEntry.equals(bag[index]))
{
found = true ;
} // end if
} // end for
return found;
} // end contains
The structure of the loop is suitable for the method getIndexOf , but we must save the value of
index when the entry is found. The method will return this index instead of a boolean value.
2.28
The definition of getIndexOf . To revise the loop in contains for use in getIndexOf , we define an
integer variable where to record the value of index when anEntry equals bag[index] . Thus, the
definition of getIndexOf looks like this:
// 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 found = false ;
for ( int index = 0; !found && (index < numberOfEntries); index++)
{
if (anEntry.equals(bag[index]))
{
found = true ;
where = index;
} // end if
} // end for
// Assertion: If where > -1, anEntry is in the array bag, and it
// equals bag[where]; otherwise, anEntry is not in the array
return where;
} // end getIndexOf
The method getIndexOf returns the value of where . Notice that we initialize where to -1, which is
the value to return if anEntry is not found.
Question 16 What assert statement can you add to the definition of the method getIndexOf
just before the return statement to indicate the possible values that the method can return?
Question 17 Revise the definition of the method getIndexOf so that it does not use a
boolean variable.
 
Search WWH ::




Custom Search