Java Reference
In-Depth Information
A performance penalty is incurred when a Vector 's capacity is exceeded. So
under some circumstances it might be advantageous to allocate capacity for a Vec-
tor , especially one that will hold large numbers of elements (more than 50 or so).
The default for a Vector is to allocate space for 10 elements and to increment by 10.
Actually, using Vectors and ArrayLists in your program is a little more com-
plex than it would seem. This is because you have to use the proper method when
you add, change, or retrieve objects from a Vector . Furthermore, Vectors and
ArrayLists store only objects, not specific class types. Subsequently, any object re-
trieved from them must be cast back into the correct class before it can be properly
used, if you do not store the same Generic type definition specified when the col-
lection was created.
Let's contrast the statements necessary to access elements in an array with the
way you would manage elements in an ArrayList :
// Define an array of five error messages.
ErrorMsg[] errorMsgs = new ErrorMsg[5];
// Add some elements to the array.
errorMsgs[0] = myErrorMsg;
errorMsgs[1] = myotherErrorMsg;
// Modify the first element in the array.
errorMsgs[0] = mythirdErrorMsg;
// Retrieve the first element in the array.
myErrorMsg = errorMsgs[0];
// Create a potential problem because errorMsgs may not be large enough to
// contain all of the error messages in ErrorMsgIO.
for (int x = 0; x < errorMsgIO.length; x++) {
errorMsgs[x] = errorMsgIO[x]
...
}
// Retrieve the number of elements in errorMsgs.
int y = errorMsgs.length;
This is how you could code ErrorMsgs as an ArrayList :
// Define an ArrayList that will contain ErrorMsgs.
ArrayList<ErrorMsg> errorMsgs = new ArrayList<ErrorMsg> ();
// Add some elements to the list.
errorMsgs.add (myErrorMsg);
errorMsgs.add (myotherErrorMsg);
// Modify the first element in the list.
errorMsgs.set (0, mythirdErrorMsg);
// Retrieve the first element from the list.
myErrorMsg = errorMsgs.get (0);
Search WWH ::




Custom Search