Java Reference
In-Depth Information
A
NSWERS
TO
S
ELF
-T
EST
Q
UESTIONS
1.
SortedListInterface<String> sortedWordList =
new
SortedList<String>();
int
numberOfWords = wordList.getLength();
for
(
int
position = 1; position <= numberOfWords; position++)
sortedWordList.add(wordList.getEntry(position));
2.
a.
int
length = sortedWordList.getLength();
String lastEntry = sortedWordList.getEntry(length);
System.out.println(lastEntry);
b.
sortedList.add(sortedList.getEntry(1));
3.
The order is critical. When
currentNode
is
null
,
currentNode
!=
null
is false. Thus, the entire expression in the
while
statement is false without executing the call
currentNode.getData()
. If the latter call were to execute first
when
currentNode
was
null
, an exception would occur. Thus, the
while
statement should remain as written.
4.
When the sorted list is empty,
getNodeBefore
returns
null
. Thus, in the definition of
add
, you can omit the call to
isEmpty
in the
if
statement.
5.
Before the first occurrence of the entry.
6.
After the last occurrence of the entry.
7.
Before the first occurrence of the entry.
8.
The method
add(newEntry)
for a list adds a new entry at the end of the list. A tail reference makes this method
O(1) instead of O(
n
). For a sorted list,
add(newEntry)
must traverse the chain to locate the point of insertion. If
the insertion is at the end of the chain, the traversal will give you a reference to the last node. A separate tail refer-
ence is not needed.
9.
Before the first occurrence of the entry. Note that
getPosition
returns the position of the first occurrence of the
entry within the list.
10.
No. The field
list
is private so its methods are unavailable to a client of
SortedList
.
11.
The first occurrence of the object. Note that
getPosition
returns the position of the first occurrence of the entry
within the list.
12.
a.
2;
b.
-1;
c.
-5;
d.
4;
e.
-3.
13.
public
boolean
contains(T anEntry)
{
return
getPosition(anEntry) > 0;
}
// end contains
14.
The implementation that invokes
getPosition
will execute faster. Because the list is sorted, the method
getPosition
does not always search the entire list when the entry is not present. However, the list's method
contains
always
searches the entire list in this case.
15.
Advantage: The implementation is easy to write.
Disadvantage: The implementation is not efficient when the implementation of the underlying list is linked.