Java Reference
In-Depth Information
type, including another
Vector<>
. The objects are stored in the new collection class object in the sequence
in which they are returned from the iterator for the argument.
Let's see a vector working.
TRY IT OUT: Using a Vector
I take a very simple example here, just storing a few strings in a vector:
import java.util.Vector;
public class TrySimpleVector {
public static void main(String[] args) {
Vector<String> names = new Vector<>();
String[] firstnames = { "Jack", "Jill", "John",
"Joan", "Jeremiah", "Josephine"};
// Add the names to the vector
for(String firstname : firstnames) {
names.add(firstname);
}
// List the contents of the vector
for(String name : names) {
System.out.println(name);
}
}
}
TrySimpleVector.java
If you compile and run this, it lists the names that are defined in the program. The code works just as
well with
Vector
replaced by
ArrayList
.
How It Works
You first create a vector to store strings using the default constructor:
Vector<String> names = new Vector<>();
This vector has the default capacity to store ten references to strings. You copy the references to the
Vector<String>
object,
names
, in the first
for
loop. The
add()
method adds the object to the vector at
the next available position.
The second
for
loop iterates over the
String
references in the vector:
for(String name : names) {
System.out.println(name);