Java Reference
In-Depth Information
reference must change to refer to the new last entry. The following statements perform these
steps, as Figure 14-9 illustrates:
lastNode.setNextNode(newNode);
lastNode = newNode;
FIGURE 14-9
Adding a node to the end of a nonempty chain that has a tail
reference
After executing
lastNode.setNextNode(newNode);
(a)
lastNode
newNode
After executing
lastNode = newNode;
(b)
lastNode
newNode
The following revision of the first
add
method reflects the previous comments:
public void
add(T newEntry)
{
Node newNode =
new
Node(newEntry);
if
(isEmpty())
firstNode = newNode;
else
lastNode.setNextNode(newNode);
lastNode = newNode;
numberOfEntries++;
}
// end add
Note that the method no longer calls
getNodeAt
to establish
lastNode
, as it did in Segment 14.9.
14.23
Adding to the list at a given position.
Adding to a list by position affects the tail reference only
when we are adding to an empty list or adding to the end of a nonempty list. Other cases do not
affect the tail reference, so we treat them as we did in Segment 14.11 when we did not have a
tail reference.
Thus, the implementation of the method that adds by position is
public boolean
add(
int
newPosition, T newEntry)
{
boolean
isSuccessful =
true
;
if
((newPosition >= 1) && (newPosition <= numberOfEntries + 1))
{
Node newNode =
new
Node(newEntry);
if
(isEmpty())
{