Java Reference
In-Depth Information
Question 10
Revise the definition of the method
clear
so that it does not call
isEmpty
.
Hint
: The
while
statement should have an empty body.
Question 11
Consider the following definition of
clear
:
public void
clear()
{
numberOfEntries = 0;
}
// end clear
What is a disadvantage of this definition as compared to the one shown in Segment 2.20?
2.21
Removing an unspecified entry.
The method
remove
that has no parameter removes an unspecified
entry from a bag, as long as the bag is not empty. Recall from the method's specification given in the
interface in Listing 1-1 of the previous chapter that the method returns the entry it removes:
/** 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()
If the bag is empty before the method executes,
null
is returned.
Removing an entry from a bag involves removing it from an array. Although we can access
any entry in the array
bag
, the last one is easy to remove. To do so, we
Access the entry so it can be returned
●
Set the entry's array element to
null
●
Decrement
numberOfEntries
●
Decrementing
numberOfEntries
causes the last entry to be ignored, meaning that it is effectively
removed, even if we did not set its location in the array to
null
.
A literal translation of the previous steps into Java leads to the following definition of the method:
public
T remove()
{
T result =
null
;
if
(numberOfEntries > 0)
{
result = bag[numberOfEntries - 1];
bag[numberOfEntries - 1] =
null
;
numberOfEntries--;
}
// end if
return
result;
}
// end remove
Note that this method computes
numberOfEntries -
1 three times. The following refinement
avoids this repetition:
public
T remove()
{
T result =
null
;
if
(numberOfEntries > 0)
{
numberOfEntries--;
result = bag[numberOfEntries];
bag[numberOfEntries] =
null
;
}
// end if