Java Reference
In-Depth Information
If we are adding to an empty bag,
numberOfEntries
would be zero, and the assignment would be to
bag[0]
. If the bag contained one entry, an additional entry would be assigned to
bag[1]
, and so on.
After each addition to the bag, we increase the counter
numberOfEntries
. These steps are illus-
trated in Figure 2-3 and accomplished by the definition of the method
add
that follows the figure.
FIGURE 2-3
Adding entries to an array that represents a bag, whose capacity
is six, until it becomes full
bag
numberOfEntries
Empty
0
0
1
2
3
4
5
Doug
1
0
1
2
3
4
5
Doug
Nancy
Nancy
2
1
2
3
4
5
0
Doug
Nancy
Ted
Nancy
3
0
1
2
3
4
5
Doug
Nancy
Ted
Vandee
Nancy
4
1
2
3
4
5
0
Doug
Nancy
Ted Vandee
Sue
5
0
1
2
3
4
5
Full
Doug
Nancy
Sue
Frank
Ted Vandee
6
0
1
2
3
4
5
/** 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)
{
boolean
result =
true
;
if
(isFull())
{
result =
false
;
}
else
{
// assertion: result is true here
bag[numberOfEntries] = newEntry;
numberOfEntries++;
}
// end if
return
result;
}
// end add