Java Reference
In-Depth Information
{
private Vector<T> list; // entries in list
. . .
The data field list is an instance of Vector instead of an array, as it was earlier in this chapter.
Since Vector is defined in terms of a generic type, you provide a data type when declaring a vector.
However, within our class VectorList , the data type of the list's objects is still unknown, so we use
the generic type T in the declaration of the field list .
Since a vector keeps track of the number of entries it contains, a data field to count them is not
required. Any time we want to know the number of entries in the vector, and hence the list, we can
write list.size() .
13.17
The constructors. The constructors for our class create an instance of Vector by invoking Vector 's
constructors. Our default constructor simply invokes Vector 's default constructor with the generic type T :
public VectorList()
{
list = new Vector<T>();
} // end default constructor
Vector 's default constructor creates a vector that can hold 10 entries. This vector will double in
size after it becomes full.
Our second constructor enables the client to specify the initial capacity of the list. It invokes a
corresponding constructor of Vector :
public VectorList( int initialSize)
{
list = new Vector<T>(initialSize);
} // end constructor
Here, Vector 's constructor creates a vector that can hold initialSize entries. This vector also will
double in size after it becomes full.
If we wanted a different initial capacity for our default list, we could define the default constructor,
as follows, instead of as given previously:
public VectorList()
{
this (DEFAULT_INITIAL_CAPACITY);
} // end default constructor
This version of the default constructor calls VectorList 's second constructor, passing it a constant
DEFAULT_INITIAL_CAPACITY , which the class must define.
13.18
The add methods. To add to the end of a list, you use Vector 's add method. This method adds a
given object to the end of a vector. If necessary, the vector increases its capacity to accommodate
the new entry. Thus, our add method does not test whether the vector is full:
public void add(T newEntry)
{
list.add(newEntry);
} // end add
To add an entry at a given position in the list, we use another of Vector 's add methods. This
method throws an exception if newPosition is illegal, but we simply want to return false in this
case. By checking the validity of newPosition , we can avoid the exception. Remember that Vector
numbers its entries beginning with 0 instead of 1.
public boolean add( int newPosition, T newEntry)
{
boolean isSuccessful = true ;
Search WWH ::




Custom Search