Java Reference
In-Depth Information
There is yet another special case. If you ran this program, you'd find that, after all
of your hard work, the program throws a
NullPointerException
on the very first
call to
addSorted
. Java throws an exception if the list is empty because a line in the
code asks for
front.data
and
front
is
null
.
So you need to include yet another test in the code:
if (value <= front.data || front == null) {
front = new ListNode(value, front);
}
Of course, we have purposely written this addition in the wrong way as well. This
is another example of a sensitive test (referring to
front.data
) and a robust test
(testing
front
for
null
). So you have to reverse the order of these two tests to make
the modification to the code work properly.
The final version of the method is as follows:
public void addSorted(int value) {
if (front == null || front.data >= value) {
front = new ListNode(value, front);
} else {
ListNode current = front;
while (current.next != null && current.next.data < value) {
current = current.next;
}
current.next = new ListNode(value, current.next);
}
}
The
if
statement in this code deals with the two special cases we just mentioned.
If the list is currently empty (
front == null
) or if the value belongs at the front of
the list (
front.data >= value
), then you insert the value at the front of the list
rather than using the other code that you developed. The order in which this test
appears is important because the test involving
front.data
will throw a
NullPointerException
if
front
is
null
.
This code is a good example to study because it has so many special cases. In the
course of writing the code, you had to deal with the following cases:
•
middle:
the “typical” case in which a value is inserted in the middle of the list
•
back:
the special case in which we had to insert at the back of the list
•
front:
the special case in which we had to insert at the front of the list
•
empty:
the special case in which we had to insert into an empty list
Search WWH ::
Custom Search