Java Reference
In-Depth Information
Revise the definition of the method
add
to always accommodate a new entry. The method
will never return false.
●
Revise the definition of the method
isFull
to always return false. A bag will never become full.
●
Revising the method
add
is the only substantial task in this list. The rest of the class will remain
unchanged.
2.37
The method
add
.
Here is the original definition of the method
add
, as it appears in Segment 2.10:
/** Adds a new entry to this bag.
@param newEntry the object to be added as a new entry
@return true if the addition is successful, or false if not */
public boolean
add(T newEntry)
{
boolean
result =
true
;
if
(isFull())
{
result =
false
;
}
else
{
// assertion: result is true here
bag[numberOfEntries] = newEntry;
numberOfEntries++;
}
// end if
return
result;
}
// end add
Since the bag will never be full, the method
isFull
will always return false. Thus, we can no lon-
ger call
isFull
to see whether the array
bag
is full. Instead, we can define a private method to both
make this check and resize the array
bag
, if necessary. Let's name the method
ensureCapacity
and
specify it as follows:
// Doubles the size of the array bag if it is full.
private void
ensureCapacity()
Assuming that we have defined this private method, we can revise the method
add
as follows:
public boolean
add(T newEntry)
{
ensureCapacity();
bag[numberOfEntries] = newEntry;
numberOfEntries++;
return true
;
}
// end add
2.38
The private method
ensureCapacity
. The array
bag
is full when
numberOfEntries
equals the
array's length,
bag.length
. When that is the case, we will resize
bag
using the technique described
earlier in Segment 2.34. Thus, the definition of
ensureCapacity
is straightforward:
// Doubles the size of the array bag if it is full.
private void
ensureCapacity()
{
if
(numberOfEntries == bag.length)
bag = Arrays.copyOf(bag, 2 * bag.length);
}
// end ensureCapacity
2.39
The class
ResizableArrayBag
.
Our new class is available online from the topic's website. You
should examine its details.