Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Collections
-
Collections store multiple objects in Java. For our purposes, let's
consider ArrayLists
and Vectors.
-
They are kind of like Arrays, but they are more flexible. With an
Array, you have to declare the number of elements and you cannot exceed
that maximum number.
-
Vectors were first in Java. They store all objects as class Object.
-
You add objects to Vectors with the addElement(Object o); method.
This adds the object to the end of the Vector, and increases the size of
the Vector, if necessary.
-
Then, you can get an object out of a Vector with the elementAt(int
index); method. This returns the object at the specified index.
-
You can often use this in a loop, where the index is the iteration of the
loop. If you had a for loop set up as: for (int i = 0; i <
vtrMyVector.size(); i++), you might use i in the body of
the loop to get out each element of the vector.
-
And, as you can see above, you can use the size() method of the Vector
object to find the number of elements in the Vector.
-
ArrayLists came in Java 1.2. They are a bit more efficient, because
they are not thread safe. Vectors are thread safe, which make them
slower.
-
ArrayLists operate on many of the same principles. They have a size()
method, like Vectors. They do not have addElement
and elementAt methods, but they do have add(Object o)
and get(int index) methods, which perform the same tasks.



Created by: Brandan
Jones January 4, 2002