Java Reference
In-Depth Information
compiler will evaluate the type of each object that is placed into the collection and
report any invalid object types as compile-time errors.
Vector< ErrorMsg > errorMsgsVector = new Vector< ErrorMsg > ();
ArrayList< ErrorMsg > errorMsgsList = new ArrayList< ErrorMsg > ();
Both Vector and ArrayList have constructors that pass an integer for the ca-
pacity of the collection. The capacity value is merely the initial capacity and, if the
constructor without it is used, a default value for initial capacity is used.
Vectors and ArrayLists have a size attribute. Size is the number of elements
currently in the Vector . The sample Vector so far has a size of zero (no elements in
the Vector ). The values of this attribute can be accessed with the size() methods.
To add elements to the Vector , use the addElement() method. To add elements
to the ArrayList , use the add() method. This places a new element in the Vector in
the next available position and increases the size of the Vector by 1.
// Create some objects.
ErrorMsg myErrorMsg = new ErrorMsg ();
ErrorMsg myotherErrorMsg = new ErrorMsg ("Some Text");
ErrorMsg mythirdErrorMsg = new ErrorMsg ("Third One");
// Place them in the Vector.
errorMsgsVector.addElement (myErrorMsg);
errorMsgsVector.addElement (myotherErrorMsg);
errorMsgsVector.addElement (mythirdErrorMsg);
// Place them in the ArrayList.
errorMsgsList.add(myErrorMsg);
errorMsgsList.add(myotherErrorMsg);
errorMsgsList.add(mythirdErrorMsg);
Now the Vector and ArrayList both have a size of three.
A Vector and ArrayList will automatically expand when their capacities are ex-
ceeded. If you were to add 11 items to the Vector , then the Vector would resize it-
self (and probably relocate itself in memory). The default behavior is to double in
size whenever the current capacity is exceeded. Defining an increment value when
the Vector is first created will control how the Vector is expanded:
Vector errorMsgs = new Vector (10, 20);
This Vector will have an initial capacity of 10 and will increment by 20 element
positions whenever its current capacity is exceeded (that is, first 10, then 30, then
50 elements).
Search WWH ::




Custom Search