Java Reference
In-Depth Information
Each time we find a match, we increment a counter. When the loop ends, we simply return the value
of the counter. Note that we must use the method
equals
to compare objects. That is, we must write
anEntry.equals(bag[index])
and not
anEntry == bag[index]
// WRONG!
We assume that the class to which the objects belong defines its own version of
equals
.
The method definition follows:
/** 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
counter = 0;
for
(
int
index = 0; index < numberOfEntries; index++)
{
if
(anEntry.equals(bag[index]))
{
counter++;
}
// end if
}
// end for
return
counter;
}
// end getFrequencyOf
2.18
The method
contains
.
To see whether a bag contains a given object, we once again search the
array
bag
. The loop we need here is similar to the one in the method
getFrequencyOf
, but it should
stop as soon as it finds the first occurrence of the desired entry. The following pseudocode
describes this logic:
while
(anEntry
is not found and we have more array elements to check
)
{
if
(anEntry
equals the next array entry
)
anEntry
is found in the array
}
This loop terminates under one of two conditions: Either
anEntry
has been found in the array or the
entire array has been searched without success.
Here, then, is our definition of the method
contains
:
/** 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)
{
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