Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

488 Part II: The Java Library


Framework. With the advent of collections,Vectorwas reengineered to extendAbstractListand
to implement theListinterface. With the release of JDK 5, it was retrofitted for generics and
reengineered to implementIterable. This means thatVectoris fully compatible with collections,
and aVectorcan have its contents iterated by the enhancedforloop.
Vectoris declared like this:

class Vector<E>

Here,Especifies the type of element that will be stored.
Here are theVectorconstructors:

Vector( )
Vector(intsize)
Vector(intsize, intincr)
Vector(Collection<? extends E>c)

The first form creates a default vector, which has an initial size of 10. The second form creates
a vector whose initial capacity is specified bysize.The third form creates a vector whose
initial capacity is specified bysizeand whose increment is specified byincr.The increment
specifies the number of elements to allocate each time that a vector is resized upward. The
fourth form creates a vector that contains the elements of collectionc.
All vectors start with an initial capacity. After this initial capacity is reached, the next
time that you attempt to store an object in the vector, the vector automatically allocates
space for that object plus extra room for additional objects. By allocating more than just the
required memory, the vector reduces the number of allocations that must take place. This
reduction is important, because allocations are costly in terms of time. The amount of extra
space allocated during each reallocation is determined by the increment that you specify
when you create the vector. If you don’t specify an increment, the vector ’s size is doubled
by each allocation cycle.
Vectordefines these protected data members:

int capacityIncrement;
int elementCount;
Object[ ] elementData;

The increment value is stored incapacityIncrement. The number of elements currently in the
vector is stored inelementCount. The array that holds the vector is stored inelementData.
In addition to the collections methods defined byList,Vectordefines several legacy
methods, which are summarized in Table 17-15.
BecauseVectorimplementsList, you can use a vector just like you use anArrayList
instance. You can also manipulate one using its legacy methods. For example, after you
instantiate aVector, you can add an element to it by callingaddElement( ). To obtain the
element at a specific location, callelementAt( ). To obtain the first element in the vector, call
firstElement( ). To retrieve the last element, calllastElement( ). You can obtain the index of an
element by usingindexOf( )andlastIndexOf( ). To remove an element, callremoveElement( )
orremoveElementAt( ).
Free download pdf