Java Reference
In-Depth Information
Before we implement this private method, let's see if we can use it by revising the
remove
method in Segment 2.21. Since that method removes and returns the last entry in the array
bag
, that is,
bag[numberOfEntries - 1]
, its definition can make the call
removeEntry(numberOfEntries - 1)
.
Proceeding as if
removeEntry
were defined and tested, we can define
remove
as follows:
/** Removes one unspecified entry from this bag, if possible.
@return either the removed entry, if the removal was successful,
or null otherwise */
public
T remove()
{
T result = removeEntry(numberOfEntries - 1);
return
result;
}
// end remove
This definition looks good; let's implement the second
remove
method.
2.25
The second
remove
method.
The first
remove
method does not search for the entry to remove, as it
removes the last entry in the array. The second
remove
method, however, does need to perform a
search. Rather than thinking about the details of locating an entry in an array right now, let's dele-
gate that task to another private method, which we specify as follows:
// Locates a given entry within the array bag.
// Returns the index of the entry, if located, or -1 otherwise.
private int
getIndexOf(T anEntry)
Assuming that this method is defined and tested, we can define our public method as follows:
/** Removes one occurrence of a given entry from this bag.
@param anEntry the entry to be removed
@return true if the removal was successful, or false if not */
public boolean
remove(T anEntry)
{
int
index = getIndexOf(anEntry);
T result = removeEntry(index);
return
anEntry.equals(result);
}
// end remove
Notice that
removeEntry
returns either the entry it removes or
null
. That is exactly what the first
remove
method needs, but the second
remove
method has to return a boolean value. Thus, in the second
method we need to compare the entry we want to remove with the one
removeEntry
returns to get the
desired boolean value.
Question 14
Can the
return
statement in the previous definition of
remove
be written as
follows?
a.
return
result.equals(anEntry);
b.
return
result !=
null
;
Question 15
The array
bag
in
ArrayBag
contains the entries in the bag
aBag
. If
bag
con-
tains the strings
"A"
,
"A"
,
"B"
,
"A"
,
"C"
, why does
aBag.remove("B")
change the contents
of
bag
to
"A"
,
"A"
,
"C"
,
"A", null
instead of either
"A"
,
"A"
,
"A"
,
"C", null
or
"A"
,
"A"
,
null
,
"A"
,
"C"
?
2.26
The definition of the private method
removeEntry
.
Let's look back at the pseudocode we wrote
in Segment 2.23 for removing a particular entry from the bag. The private method
removeEntry