Java Reference
In-Depth Information
Within the body of the loop, we access the data in the current node and compare it with the
entry passed to the method as its argument. Each time we find a match, we increment a frequency
count. Thus, we have the following definition for the method getFrequencyOf :
/** Counts the number of times a given entry appears in this bag.
@param anEntry the entry to be counted
@return the number of times anEntry appears in the bag */
public int getFrequencyOf(T anEntry)
{
int frequency = 0;
int counter = 0;
Node currentNode = firstNode;
while ((counter < numberOfEntries) && (currentNode != null ))
{
if (anEntry.equals(currentNode.data))
frequency++;
counter++;
currentNode = currentNode.next;
} // end while
return frequency;
} // end getFrequencyOf
The Method contains
3.17
In the previous chapter—where we used an array to represent the bag's entries—we determined
whether a bag contained a given entry by examining each array element—starting at index zero—
until we either found the desired entry or discovered that it was not in the array. We use an analo-
gous approach here to search a chain for a particular piece of data by looking at the chain's nodes,
one at a time. We begin at the first node, and if that does not contain the entry we are seeking, we
look at the second node, and so on.
When searching an array, we use an index. To search a chain, we use a reference to a node. So,
just as in the method getFrequencyOf , we use a local variable currentNode to reference the node
that we want to examine. Initially, we set currentNode to firstNode and then to currentNode.next
as we traverse the chain. However, instead of traversing the entire chain, our loop iterates until either
we find the desired entry or currentNode becomes null —in which case the entry is not in the bag.
Thus, the method contains has the following implementation:
public boolean contains(T anEntry)
{
boolean found = false ;
Node currentNode = firstNode;
while (!found && (currentNode != null ))
{
if (anEntry.equals(currentNode.data))
found = true ;
else
currentNode = currentNode.next;
} // end while
return found;
} // end contains
 
 
Search WWH ::




Custom Search