Java Reference
In-Depth Information
result = nodeToRemove.getData();
// save entry to be removed
}
// end if
numberOfEntries--;
}
// end if
return
result;
// return removed entry, or
// null if operation fails
}
// end remove
Notice that we use the private method
getNodeAt
, which we wrote originally for the
add
meth-
ods, to locate the node before the one to be removed. This method is called only when we remove
an entry other than the first one. Thus, its argument
givenPosition
-
1
will always be greater than
zero, as its precondition requires.
Also notice that we do not explicitly set
nodeToRemove
to
null
after disconnecting the node.
This variable is local to the
remove
method and so does not exist after the method completes execu-
tion. Although we could set
nodeToRemove
to
null
, doing so is not necessary.
Question 13
Why is the assertion in the previous method true?
14.17
The method
replace
.
Replacing a list entry requires us to replace the data portion of a node with
other data. We can use the private method
getNodeAt
to locate the node and then simply replace its
data portion. Before calling
getNodeAt
, we check that the list is not empty and the given position is
valid. The implementation appears as follows:
public boolean
replace(
int
givenPosition, T newEntry)
{
boolean
isSuccessful =
true
;
if
((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
assert
!isEmpty();
Node desiredNode = getNodeAt(givenPosition);
desiredNode.setData(newEntry);
}
else
isSuccessful =
false
;
return
isSuccessful;
}
// end replace
Note:
The method
replace
replaces the data in a node, but not the node itself.
Question 14
Compare the time required to replace an entry in a list using the previous
method
replace
with the time required for the array-based version given in Segment 13.12.
14.18
The method
getEntry
.
Retrieving a list entry is straightforward:
public
T getEntry(
int
givenPosition)
{
T result =
null
;
// result to return