Java Reference
In-Depth Information
/** Adds a new entry to this bag.
@param newEntry the object to be added as a new entry
@return true if the addition is successful, or false if not */
public boolean add(T newEntry)
{
< Body to be defined >
} // end add
/** Retrieves all entries that are in this bag.
@return a newly allocated array of all the entries in the bag */
public T[] toArray()
{
< Body to be defined >
} // end toArray
/** Sees whether this bag is full.
@return true if the bag is full, or false if not */
public boolean isFull()
{
< Body to be defined >
} // end isFull
< Similar partial definitions are here for the remaining methods
declared in BagInterface . >
. . .
} // end ArrayBag
Design Decision: When the array bag is partially full, which array elements should
contain the bag's entries?
When you add a first entry to an array, you typically place it in the array's first element, that is, the
element whose index is 0. Doing so, however, is not a requirement, especially for arrays that imple-
ment collections. For example, some collection implementations can benefit by ignoring the array
element whose index is 0 and using index 1 as the first element in the array. Sometimes you might
want to use the elements at the end of the array before the ones at its beginning. For the bag, we
have no reason to be atypical, and so the objects in our bag will begin at index 0 of the array.
Another consideration is whether the bag's objects should occupy consecutive elements of the
array. Requiring the add method to place objects into the array bag consecutively is certainly rea-
sonable, but why should we care, and is this really a concern? We need to establish certain truths, or
assertions, about our planned implementation so that the action of each method is not detrimental to
other methods. For example, the method toArray must “know” where add has placed the bag's
entries. Our decision now also will affect what must happen later when we remove an entry from
the bag. Will the method remove ensure that the array entries remain in consecutive elements? It
must, because for now at least, we will insist that bag entries occupy consecutive array elements.
2.10
The method add . If the bag is full, we cannot add anything to it. In that case, the method add
should return false. Otherwise, we simply add newEntry immediately after the last entry in the
array bag by writing the following statement:
bag[numberOfEntries] = newEntry;
 
Search WWH ::




Custom Search