Java Reference
In-Depth Information
return result;
} // end remove
Question 12 Why does the method remove set bag[numberOfEntries] to null ?
Question 13 The previous remove method removes the last entry in the array bag . Why
might removing a different entry be more difficult to accomplish?
2.22
Removing a given entry. Our third method that removes an entry from the bag involves removing
a given entry —call it anEntry . If the entry occurs more than once in the bag, we will remove only
one occurrence. Exactly which occurrence is removed is unspecified. We will simply remove the
first occurrence of anEntry that we encounter while searching for it. As we discussed in
Segment 1.9 of Chapter 1, we will return either true or false, according to whether we find the entry
in the bag.
Assuming that the bag is not empty, we search the array bag much as the method contains did
in Segment 2.18. If anEntry equals bag[index] , we note the value of index . Figure 2-5 illustrates
the array after a successful search.
FIGURE 2-5
The array bag after a successful search for the string "Alice"
bag[index]
Doug
Alice
Ted Vandee
Sue
Nancy
Indices
0
1
2
3
4
5
6
index
We now need to remove the entry in bag[index] . If we simply write
bag[index] = null ;
the reference in bag[index] to the entry will be removed, but we will have a gap in the array. That is, the
contents of the bag will no longer be in consecutive array locations, as Figure 2-6a illustrates. We could get
rid of that gap by shifting the subsequent entries, as shown in Figure 2-6b. This time-consuming approach
is not necessary, however.
FIGURE 2-6
(a) A gap in the array bag after setting the entry in bag[index] to
null ; (b) the array after shifting subsequent entries to avoid a gap
bag[index]
(a)
Doug
Sue
Nancy
Ted Vandee
null
(b)
Doug
Nancy
Ted
Vandee
Sue
0
1
2
3
4
5
6
Search WWH ::




Custom Search