Java Reference
In-Depth Information
14.11
The Java method.
The following implementation of the
add
method is based on the previous
code fragments. We begin by checking the validity of the insertion position,
newPosition
. If it is
within range, we create the new node. We then insert the new node into the chain according to its
intended position,
newPosition
: The insertion is either at the beginning of the list or somewhere
else in the list.
public boolean
add(
int
newPosition, T newEntry)
{
boolean
isSuccessful =
true
;
if
((newPosition
>
= 1) && (newPosition <= numberOfEntries + 1))
{
Node newNode =
new
Node(newEntry);
if
(newPosition == 1)
// case 1
{
newNode.setNextNode(firstNode);
firstNode = newNode;
}
else
// case 2: list is not empty
{
// and newPosition > 1
Node nodeBefore = getNodeAt(newPosition - 1);
Node nodeAfter = nodeBefore.getNextNode();
newNode.setNextNode(nodeAfter);
nodeBefore.setNextNode(newNode);
}
// end if
numberOfEntries++;
}
else
isSuccessful =
false
;
return
isSuccessful;
}
// end add
Question 6
Consider the first
else
clause of the previous method
add
.
a.
What
assert
statement could you add to this clause?
b.
What call to
getNodeAt
could replace the value assigned to
nodeAfter
?
c.
Should we make the change suggested in Part
b
?
Question 7
In the previous method
add
, the second
if
statement tests the value of
new
Position
. Should the boolean expression it tests be
isEmpty()
||
(newPosition == 1)
?
Explain.
Question 8
How do the
add
methods given in Segments 14.9 and 14.11 enforce the pre-
condition of
getNodeAt
?
14.12
The method
isEmpty
and assertions.
The implementation of the method
isEmpty
could simply
test that the length of the list is zero, as it did in the array-based implementations that you saw in the
previous chapter. However, we have another criterion that we could use here. When a list is empty,
the reference
firstNode
is
null
. If our implementation is correct, either criterion is fine, but what
happens during development when some part of our class might contain an error in logic? We can