Vector Overview
Vector is very similar to ArrayList except that Vector is synchronized collection unlike ArrayList which is non-synchronized
Features of Vector are as below
Vector maintains insertion order
Vector allows duplicate elements
Vector is synchronized collection
Since vector is synchronized, it takes performance hit and hence its not good to use in non-threaded environment
Vector can be instantiated as
- Vector v = new Vector();
Vector v = new Vector();
It creates an empty Vector with the default initial capacity of 10
Example :
- import java.util.*;
- public class VectorExample {
- public static void main(String args[]) {
- Vector<String> vector = new Vector<String>();
- vector.addElement("c");
- vector.addElement("c++");
- vector.addElement("java");
- System.out.println("Size of Vector is: "+vector.size());
- System.out.println("Capacity before increment is: "+vector.capacity());
- vector.addElement("machine learning");
- vector.addElement("big data");
- vector.addElement("cloud");
- System.out.println("Size after addition: "+vector.size());
- System.out.println("Capacity after increment is: "+vector.capacity());
- Enumeration en = vector.elements();
- System.out.println("\nElements are:");
- while(en.hasMoreElements())
- System.out.print(en.nextElement() + " ");
- }
- }
import java.util.*; public class VectorExample { public static void main(String args[]) { Vector<String> vector = new Vector<String>(); vector.addElement("c"); vector.addElement("c++"); vector.addElement("java"); System.out.println("Size of Vector is: "+vector.size()); System.out.println("Capacity before increment is: "+vector.capacity()); vector.addElement("machine learning"); vector.addElement("big data"); vector.addElement("cloud"); System.out.println("Size after addition: "+vector.size()); System.out.println("Capacity after increment is: "+vector.capacity()); Enumeration en = vector.elements(); System.out.println("\nElements are:"); while(en.hasMoreElements()) System.out.print(en.nextElement() + " "); } }
Note : Capacity will be doubled after adding 11th element to the Vector as Default capacity is 10