The Vector
, in Java, effectively implements a dynamic array like in other languages. This is because Java’s array is static in size, like the one’s found in C/C++.
The vector can use an index to identify a specific element, however, it can grow and shrink based upon the size needs of the vector.
Since early on, but not the beginning, the Vector class implements the List interface, so it is part of the Java Collections Framework. The Vector is Thread Safe, but if you don’t need a thread safe version, you can use ArrayList
instead, which might provide a little performance improvement.
One thing to mention about Vectors is that they provide access to a dynamic array of Objects, but not primitives. That is because they will use Java’s (and Object Oriented) Polymorphism to allow the stored object to act as any object we choose.
By default, a Vector is created with ten (10) elements, however, it’s constructor is overloaded to allow you to pass in a collection, or set a different initial amount. Additionally, you can tell Java how many elements to grow by if necessary.
It is recommended to parameterize your constructor and data type.
Vector<String> vector1 = new Vector<String>();
Vector<String> vector2 = new Vector<String>(20);
Vector<String> vector3 = new Vector<String>(200,50);
Consider the following code, and review it’s output.
public static void main(String args[]) {
Vector<String> vector1 = new Vector<String>();
Vector<String> vector2 = new Vector<String>(200);
vector1.add("Bob");
vector2.add("Hello");
System.out.println(vector1.size());
System.out.println(vector2.size());
System.out.println(vector1.capacity());
System.out.println(vector2.capacity());
System.out.println(vector1.get(0));
System.out.println(vector1.elementAt(0));
}
Notice how the size()
of the vector references how many elements are stored in the vector, not how big it is. You must use capacity()
to get a similar method to an array’s length
property.
You can also notice that get()
and elementAt()
are basically aliased. However, you cannot use bracket notation to access the element you want. This is because the Vector is a Class, and not a direct data type like an array.
If you specify an element outside of the range of elements that have been entered, you will get an ArrayIndexOutOfBoundsException
Exception.
Java’s Vector Class was originally found on Access 2 Learn
One Comment
Comments are closed.