Java Reference
In-Depth Information
Figure 3-9 shows the chain after the first two steps take place. Notice that the first desk is no longer
a part of the chain. Technically, it still references the second desk. But if this desk is ever used
again, a new address will be written on its paper.
FIGURE 3-9
A chain of desks just after removing its first desk
3.20
Case 2. Remember that a bag does not order its entries in any particular way. Thus, in our analo-
gous classroom, we assume that the students are seated in no particular order. If you want to drop
the course and are not seated at the first desk in the chain, we do not have to remove your desk.
Instead, we take the following steps:
1.
Move the student in the first desk to your former desk.
2.
Remove the first desk using the steps described for Case 1.
In effect, we have changed Case 2 into Case 1, which we know how to handle.
Question 7 What steps are necessary to remove the first desk in a chain of five desks?
Question 8 What steps are necessary to remove the third desk in a chain of five desks?
The Methods remove and clear
3.21
Removing an unspecified entry. The method remove without a parameter removes an unspecified
entry from a bag that is not empty. According to the method's specification, as given in the interface in
Listing 1-1 of Chapter 1, the method returns the entry it removes:
/** Removes one unspecified entry from this bag, if possible.
@return either the removed object, if the removal was successful,
or null */
public T remove()
If the bag is empty before the method executes, null is returned.
Removing an entry from a bag involves removing it from a chain of linked nodes. Since the
first node is easy to remove from the chain, we can define remove so that it removes the entry in
this first node. To do so, we take the following steps:
Access the entry in the first node so it can be returned.
Set firstNode to reference the second node, as Figure 3-10 indicates. If a second node does
not exist, set firstNode to null .
Decrement numberOfEntries .
 
 
Search WWH ::




Custom Search