Java Reference
In-Depth Information
WARNING Like arrays, array collection class objects hold object references, not actual ob-
jects. To keep the text simple I refer to a collection as holding “objects," rather than saying
“references to objects." However, you should keep in mind that all the collection classes hold
references.
Creating a Vector
The default constructor creates an empty Vector<> object with the capacity to store objects of the type ar-
gument that you supply. The default capacity of a Vector<> object is 10 objects, and the capacity doubles
when you add an object when the container is full. For example:
Vector<String> transactions = new Vector<>();
This statement creates an empty vector with a capacity for storing references to 10 String objects. You
can set the initial capacity of the Vector<> object explicitly when you create it by using a different con-
structor. You just specify the capacity you require as an argument of type int . For example:
Vector<String> transactions = new Vector<>(100);
The object you're defining here will have the capacity to store 100 strings initially. It also doubles in
capacity each time you exceed the current capacity. The process of doubling the capacity of a vector when
more space is required can be quite inefficient. For example, if you add 7,000 String object references to
the vector you have just defined, it actually has space for 12,800 object references. The capacity-doubling
mechanism means that the capacity is always a value of the form 100 ×2 n , and the smallest n to accommod-
ate 7,000 references is 128. As each object reference requires 4 bytes (on a 32-bit JVM), you are occupying
more than 20K bytes unnecessarily.
You have a way of avoiding this with a Vector<T> that is not available with the ArrayList<T> class.
You can specify the amount by which the vector should be incremented as well as the initial capacity when
you create it. Both arguments to the constructor are of type int . For example
Vector<String> transactions = new Vector<>(100,10);
This object has an initial capacity of 100, but the capacity is only increased by 10 elements when more
space is required.
NOTE Why not increment the vector object by one each time then? The process of increment-
ingthecapacitytakestimebecauseitinvolvescopyingthecontentsofthevectortoanewarea
ofmemory.Thebiggerthevectoris,thelongerthecopytakes,andthataffectsyourprogram's
performance if it happens very often.
You can create a vector or an array list collection that contains objects from another collection. You pass
the collection to the constructor as an argument of type Collection<> . Because all the set and list collec-
tion classes implement the Collection<> interface, the constructor argument can be of any set or list class
Search WWH ::




Custom Search