Java Reference
In-Depth Information
A NSWERS TO S ELF -T EST Q UESTIONS
1.
The students remain in consecutively numbered desks. You do not have to keep track of the locations of the
empty desks.
2.
Time is saved by not moving a student.
3.
The student in the highest-numbered desk.
4.
No. The two values are equal only when a bag is full.
5.
If the client contained a statement such as
Object[] bagContents = myBag.toArray();
myBag.getCurrentSize() would be the number of entries in the array bagContents . With the proposed design,
bagContents.length could be larger than the number of entries in the bag.
6.
The statements set the first element of bag to null . The value of numberOfEntries does not change, so it is 5.
7.
public T[] toArray()
{
return Arrays.copyOf(bag, bag.length);
} // end toArray
8.
The bag aBag is empty. When displayBag is called, the statement
Object[] bagArray = aBag.toArray();
executes. When toArray is called, the statement
T[] result = (T[]) new Object[numberOfEntries];
executes. Since aBag is empty, numberOfEntries is zero. Thus, the new array, result , is empty. The loop in
toArray is skipped and the empty array is returned and assigned to bagArray . Since bagArray.length is zero, the
loop in displayBag is skipped. The result of the call displayBag(aBag) is simply the line
The bag contains
9.
Advantage: This definition is easier to write, so you are less likely to make a mistake.
Disadvantage: This definition takes more time to execute, if the bag contains more than one occurrence of anEntry .
Note that the loop in the method getFrequencyOf cycles through all of the entries in the bag, whereas the loop in the
method contains , as given in Segment 2.18, ends as soon as the desired entry is found.
10.
public void clear()
{
while (remove() != null )
{
} // end while
} // end clear
11.
Although the bag will appear empty to both the client and the other methods in ArrayBag , the references to
the removed objects will remain in the array bag . Thus, the memory associated with these objects will not be
deallocated.
12.
By setting bag[numberOfEntries] to null , the method causes the memory assigned to the deleted entry to be
recycled, unless another reference to that entry exists in the client.
13.
An entry in the array bag , other than the last one, would be set to null . The remaining entries would no longer be
in consecutive elements of the array. We could either rearrange the entries to get rid of the null entry or modify
other methods to skip any null entry.
Search WWH ::




Custom Search