Java Reference
In-Depth Information
Question 9 Suppose that the implementation of the method isEmpty contains the follow-
ing single statement:
return (numberOfEntries == 0) && (firstNode == null );
If we make the error in the method add that is described in the previous segment, what happens
when add is called and the list is empty? Assume that assertions are enabled.
14.14
The method toArray . By implementing the method toArray , we will be able to test the previous
methods that we have written before we complete the rest of LList . The method must traverse the
chain and copy the data in each node to an element within an array. Thus, it needs a local variable to
reference each node in the chain. For example, currentNode could reference the node whose data
we want to copy. That data is currentNode.getData() .
Initially, we want currentNode to reference the first node in the chain, so we set it to firstNode .
To make currentNode reference the next node, we would execute the statement
currentNode = currentNode.getNextNode();
Thus, we can write a loop that iterates until currentNode becomes null .
The following method toArray uses these ideas:
public T[] toArray()
{
// the cast is safe because the new array contains null entries
@SuppressWarnings( "unchecked" )
T[] result = (T[]) new Object[numberOfEntries];
int index = 0;
Node currentNode = firstNode;
while ((index < numberOfEntries) && (currentNode != null ))
{
result[index] = currentNode.getData();
currentNode = currentNode.getNextNode();
index++;
} // end while
return result;
} // end toArray
Question 10 In the previous implementation of toArray , the while statement tests the val-
ues of both index and currentNode . Can you replace the while statement with
a. while (index < numberOfEntries)
b. while (currentNode != null )
Explain your responses.
Question 11 Compare the work required by the loop in the previous method toArray with
that required by the following version of the loop:
int index = 0;
Node currentNode = firstNode;
while ((index < numberOfEntries) && (currentNode != null ))
{
currentNode = getNodeAt(index + 1);
result[index] = currentNode.getData();
index++;
} // end while
Search WWH ::




Custom Search