Arrays have fixed length, they are not suitable for group of things that grow and shrink over the lifetime of an application. In such situations, Java provides the Vector class which is available in the standard java.util package.
A Vector is similar to an array in that it holds multiple objects and you can retrieve the stored objects by using an index value. However, the primary difference between an array and a Vector is that it can grow itself automatically when its initial capacity is exceeded. A Vector also provides methods for adding and removing elements that you would have to normally do manually in array. To sum up, the Vector class represents an ordered collection of objects that can be referenced using indexes, and can grow and shrink in size.
At any time, a Vector contains a number of elements that is less than or equal to its capacity. The capacity represents the size of the vector in memory. After the capacity is reached, the vector must grow before a new element can be added. The amount by which the Vector should grow is represented by its attribute capacity increment. If the capacity increment is 0, the array simply doubles in capacity each time its needs to grow.
The standard Vector class, java. uti1. Vector, is a parameterized class i.e. when you create an object of that class, you must supply the underlying type. For example, to create a vector of strings, the statement is
Vector<String> v = new Vector<String>();
A Vector can only add elements of object type, you cannot directly add a primitive data type such as int to a Vector
import java.util.Vector;
public class VectorinJava
{
public static void main(String[]args)
{
Vector<String> v = new Vector<String>();
String[] days = {"Mon","Tue","fri","sat"};
for(String str : days)
v.add(str);
System.out.println("No.of Elements in Vector is : "+ v.size());
v.add("sun");
v.add(2,"Wed");
System.out.println("No.of Elements in Vector is : "+ v.size());
System.out.println("First Elements in Vector is : "+v.firstElement());
System.out.println("Last Elements in Vector is : "+ v.lastElement());
System.out.println("Elements at Index 3 is : "+ v.get(3));
v.remove("Sun");
v.remove(5);
System.out.println("Element in Vector After Removel are....");
for(String str : v)
System.out.println(str);
}
}