Java Reference
In-Depth Information
Notice that we call isFull as if it has been defined already. Had we not considered isFull as a
core method earlier, its use now would indicate to us that it should be in the core group.
Note: The entries in a bag have no particular order. Thus, the method add can place a new
entry into a convenient element of the array bag . In the previous definition of add , that ele-
ment is the one immediately after the last element used.
Note: For simplicity, our figures and discussion portray arrays as if they actually contained
objects. In reality, Java arrays contain references to objects, as Figure 2-4 illustrates.
FIGURE 2-4
An array of objects contains references to those objects
Doug
Sue
Alice
Nancy
Ted Vandee
Indices
0
1
2
3
4
5
6
2.11
The method isFull . A bag is full when it contains as many objects as the array bag can accommo-
date. That situation occurs when numberOfEntries is equal to the capacity of the array. Thus,
isFull has the following straightforward definition:
/** Sees whether this bag is full.
@return true if the bag is full, or false if not */
public boolean isFull()
{
return numberOfEntries == bag.length;
} // end isFull
2.12
The method toArray . The last method, toArray , in our initial core group retrieves the entries that
are in a bag and returns them to the client within a newly allocated array. The length of this new
array can equal the number of entries in the bag—that is, numberOfEntries —rather than the length
of the array bag . However, we have the same problems in allocating an array that we had in defin-
ing the constructor, so we take the same steps as for the constructor.
After toArray creates the new array, a simple loop can copy the references in the array bag to
this new array before returning it. Thus, the definition of toArray can appear as follows:
/** Retrieves all entries that are in this bag.
@return a newly allocated array of all the entries in the bag */
public T[] toArray()
{
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] result = (T[]) new Object[numberOfEntries]; // unchecked cast
for ( int index = 0; index < numberOfEntries; index++)
{
result[index] = bag[index];
} // end for
return result;
} // end toArray
 
Search WWH ::




Custom Search