Java Reference
In-Depth Information
public ArrayBag( int capacity)
{
numberOfEntries = 0;
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempBag = (T[]) new Object[capacity]; // unchecked cast
bag = tempBag;
} // end constructor
The default constructor can invoke the previous one, passing it the default capacity as an argu-
ment, as follows:
/** Creates an empty bag whose capacity is 25. */
public ArrayBag()
{
this (DEFAULT_CAPACITY);
} // end default constructor
Recall that a constructor can invoke another constructor in the same class by using the keyword
this as a method name.
2.9
An outline of the class. Let's look at the class as we have defined it so far. After you complete the
initial portion of the class—that is, the header, data fields, and constructors—you can add the com-
ments and headers for the public methods simply by copying them from BagInterface . You then
write empty bodies after each of those headers. Listing 2-1 shows the result of these steps. Our next
task is to implement our three core methods.
LISTING 2-1
An outline of the class ArrayBag
/**
A class of bags whose entries are stored in a fixed-size array.
@author Frank M. Carrano
*/
public class ArrayBag<T> implements BagInterface<T>
{
private final T[] bag;
private static final int DEFAULT_CAPACITY = 25;
private int numberOfEntries;
/** Creates an empty bag whose initial capacity is 25. */
public ArrayBag()
{
this (DEFAULT_CAPACITY);
} // end default constructor
/** Creates an empty bag having a given initial capacity.
@param capacity the integer capacity desired */
public ArrayBag( int capacity)
{
numberOfEntries = 0;
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempBag = (T[]) new Object[capacity]; // unchecked cast
bag = tempBag;
} // end constructor
 
Search WWH ::




Custom Search