Java Reference
In-Depth Information
14.
a. No. If result were null —and that is quite possible—a NullPointerException would occur.
b. Ye s .
15.
After locating "B" in the bag, the remove method replaces it with the last relevant entry in the array bag , which is
"C" . It then replaces that last entry with null . Although we could define remove to result in either of the two other
possibilities given in the question, both choices are inferior. For example, to get "A" , "A" , "A" , "C", null ,
remove would shift the array elements, requiring more execution time. Leaving a gap in the array, such as "A" ,
"A" , null , "A" , "C" , is easy for remove to do but complicates the logic of the remaining methods.
16.
assert ((where >= 0) && (where < numberOfEntries)) || (where == -1);
17.
private int getIndexOf(T anEntry)
{
int where = -1;
for ( int index = 0; (where == -1) && (index < numberOfEntries); index++)
{
if (anEntry.equals(bag[index]))
where = index;
} // end for
return where;
} // end getIndexOf
or
private int getIndexOf(T anEntry)
{
int where = numberOfEntries - 1;
while ((where > -1) && !anEntry.equals(bag[where]))
where--;
return where;
} // end getIndexOf
18.
text = Arrays.copyOf(text, text.length + 5);
or
String[] origText = text;
text = new String[text.length + 5];
System.arraycopy(origText, 0, text, 0, origText.length);
19.
text = Arrays.copyOf(text, size);
20.
/** Creates a bag containing the given array of entries.
@param contents an array of objects */
public ResizableArrayBag(T[] contents)
{
bag = Arrays.copyOf(contents, contents.length);
numberOfEntries = contents.length;
} // end constructor
A simple assignment statement would be a poor choice, since then the client could corrupt the bag's data by
using the reference to the array that it passes to the constructor as an argument. Copying the argument array to
the array bag is necessary to protect the integrity of the bag's data.
21.
22.
Advantage: You can access any array location directly if you know its index.
Disadvantages: The array has a fixed size, so you will either waste space or run out of room. Resizing the array
avoids the latter disadvantage, but requires you to copy the contents of the original array to a larger array.
 
Search WWH ::




Custom Search