Java Reference
In-Depth Information
FIGURE 13-5
Removing Bob by shifting array entries
Alice
Bob
Carla
Doug
Haley
Alice
Carla
Carla
Doug
Haley
Alice
Carla
Doug
Doug
Haley
Haley
Haley
Alice
Carla
Doug
Alice
Carla
Doug
Haley
Note that no shift is necessary if the deletion is at the end of the list. In that case, the last entry
in the list is at position
numberOfEntries
, since the first entry is at position 1. If
givenPosition
equals
numberOfEntries
, the
for
statement in
removeGap
will exit immediately. Even so,
remove
will not call
removeGap
in this case. Notice that
removeGap
's precondition requires
givenPosition
to be less than
numberOfEntries
, and the
remove
method enforces this precondition. You can
enable the
assert
statement in
removeGap
to verify this enforcement.
This precondition of
removeGap
implies that the method should not be called if a list is empty.
In fact,
remove
ensures that requirement is followed.
Question 9
Figure 13-5 shows Haley shifted toward the beginning of the array. Actually, the
reference to Haley is copied, not moved, to its new location. Should we assign
null
to Haley's
original location?
Question 10
The method
clear
could simply set the data field
numberOfEntries
to zero.
Although the list methods would correctly behave as though the list was empty, the objects
that were in the list would remain allocated. Suggest at least two ways that
clear
could
deallocate these objects.
13.12
The methods
replace
and
getEntry
.
Replacing a list entry and retrieving a list entry are two
straightforward operations when an array is used to represent the entries. You simply replace or
retrieve the object that is in the indicated array location. Like earlier methods,
replace
and
getEntry
are responsible for validating the given position. Like
remove
, these methods do not
need an explicit test for an empty list to behave correctly. The
assert
statement is available to
verify this claim during testing.
The following methods implement these two operations:
public boolean
replace(
int
givenPosition, T newEntry)
{
boolean
isSuccessful =
true
;
if
((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
assert
!isEmpty();
list[givenPosition - 1] = newEntry;
}