Java Reference
In-Depth Information
}
All collection classes that are sequences implement the
Iterable<>
interface so you can always use the
collection-based
for
loop to access their contents. Of course, you could also use an iterator. The follow-
ing code produces the same result as the
for
loop:
java.util.Iterator<String> iter = names.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
The
iter
object provides a one-time pass through the contents of the
names
collection. The
boolean
value returned by the
hasNext()
method determines whether or not the loop should continue. The
next()
method returns the object reference as the type that you used to create the vector so no casting is
necessary.
You are spoiled for choice when accessing elements because you have a third mechanism you can use.
The
get()
method returns the reference at the index position specified by the argument to the method.
The argument is a zero-based index, just like an array. To iterate over all the index values for elements in
a vector you need to know how many elements are stored in it and the
size()
method supplies this as a
value of type
int
. You could access the elements like this:
for(int i = 0 ; i < names.size() ; ++i) {
System.out.println(names.get(i));
}
The collection-based
for
loop is the simplest and clearest mechanism for iterating over the contents of a
vector. However, the
get()
method is useful for accessing an element stored at a particular index posi-
tion.
Capacity and Size
Although I said earlier that
Vector<>
and
ArrayList<>
collections work like arrays, you can now appreci-
ate that this isn't strictly true. One significant difference is in the information you can get about the storage
space provided. An array has a single measure, its length, which is the count of the total number of elements
it can reference. Vectors and array lists have two measures relating to the space they provide: the
capacity
and the
size
. However, the capacity of an
ArrayList<>
object is not accessible.
Obtaining and Ensuring Capacity
The
capacity
is the maximum number of objects that a vector or array list can hold at any given instant. Of
course, the capacity can vary over time because when you store an object in a
Vector<>
container that is
full, its capacity automatically increases. For example, the
Vector<>
object
transactions
that you defined
in the last of the constructor examples earlier had an initial capacity of 100. You also specified the capacity
increment as 10. After you've stored 101 objects in it, its capacity is 110 objects. A vector typically contains
fewer objects than its capacity.
The
capacity()
method returns the current capacity of a vector as a value of type
int
. For example: