Java Reference
In-Depth Information
// This loop will never be a problem because ErrorMsgs will grow as required
// to contain all the error messages in ErrorMsgIO.
for (int x = 0; x < errorMsgIO.length; x++) {
errorMsgs.add (errorMsgIO[x]);
...
}
// Retrieve the number of elements in errorMsgs.
int y = errorMsgs.size();
Since Vector s and ArrayList s can contain only objects, and not primitive data
types, numeric items cannot be directly placed into Vector s. Instead, numbers must
be cast first into their object wrappers before they can be placed into a Vector array.
// Add an Integer element to an ArrayList.
ArrayList<Integer> myArrayList = new ArrayList< Integer > ();
int x = 5;
Integer myInteger = new Integer (x);
myArrayList.add (myInteger);
The autoboxing feature introduced with Java 1.5 can create these object wrap-
pers for you automatically. However, under the covers, the compiler is still creating
the integer object.
// Use Autoboxing to add an Integer element to the ArrayList.
int x = 5;
myArrayList.add (x);
Another difficulty with integer objects is that they are immutable, just like
string objects. That is, once an integer object is created, there is no way to change
its value. Instead, a new integer must be created to contain a new value. As a result,
groups of numeric values are often managed with Java arrays (which can contain
primitive data types), instead of with Vector s or ArrayLists .
You can shrink a Vector or ArrayList in order to conserve memory. The trim-
ToSize() method will truncate the Vector 's capacity to the current size. You should
perform this function only if you are sure the Vector is not likely to grow, since any
additions to the Vector will immediately cause it to be reallocated.
Following is a table showing the most commonly used ArrayList methods with
their corresponding Vector methods.
Search WWH ::




Custom Search