Java Reference
In-Depth Information
use
assert
statements involving the second criterion to help us catch an error, as in the following
version of
isEmpty
:
public boolean
isEmpty()
{
boolean
result;
if
(numberOfEntries == 0)
// or getLength() == 0
{
assert
firstNode ==
null
;
result =
true
;
}
else
{
assert
firstNode !=
null
;
result =
false
;
}
// end if
return
result;
}
// end isEmpty
14.13
Example.
Let's look at an example of how the previous implementation of
isEmpty
can help us
find an error in logic. Consider the definition of the first
add
method given in Segment 14.9. If
we had been concerned that we might forget to increment the data field
numberOfEntries
, we
might have written
numberOfEntries++
as the method's first action instead of as one of its last.
This change would have caused an error. If the list was empty when the method was called,
numberOfEntries
would have been given the value 1, and
isEmpty
would have been invoked.
Since
firstNode
would have been
null
, the second assertion within
isEmpty
would have pro-
duced an error message like the following one, assuming that we had enabled assertions:
Exception in thread “main” java.lang.AssertionError
at LList.isEmpty(LList.java:167)
at LList.add(LList.java:36)
at Driver.testList(driver.java:16)
at Driver.main(driver.java:5);
This message indicates that the method
add
called
isEmpty
, which produced the assertion
error. We could clarify this message by adding to the
assert
statements in
isEmpty
. For example, if
the second
assert
statement is
assert
firstNode !=
null
: "numberOfEntries is not 0 but firstNode is null";
the previous error message would begin as follows:
Exception in thread “main” java.lang.AssertionError:
numberOfEntries is not 0 but firstNode is null
If we ran our program without enabling assertions,
isEmpty
would simply test
numberOfEntries
.
Since
numberOfEntries
would not be zero,
isEmpty
would return false, so
add
's
else
clause would
execute. When
add
invoked
getNodeAt(1)
,
null
would be returned—since
firstNode
would be
null
—and assigned to
lastNode
. As a result,
lastNode.setNextNode(newNode)
would cause an
exception and would produce an error message such as
Exception in thread “main” java.lang.NullPointerException
at LList$Node.access$102(LList.java:212)
at LList.add(LList.java:41)
at Driver.testList(driver.java:16)
at Driver.main(driver.java:5);
This message is not as clear as the previous one, so more effort would be needed to discover
the problem.