Vector


Vector is available in java since JDK 1.0
Vector class extends AbstractList class.
 
Vector class implements following interfaces:
  • Serializable
  • Cloneable
  • Iterable
  • Collection
  • List
  • RandomAccess
The iterator returned by Vector class iterator() or listIterator() method's are failed-fast.

What is Fail-Fast: 
If the vector is structurally modified anytime after the iterator created except interator's own remove or add methods then it will throw ConcurrentModificationException

Vector class has Four constructors:

  • Vector()
  • Vector(Collection c)
  • Vector(int initialCapctity)
  • Vector(int initialCapacity, int increamentCapacity)
InitialCapacity : 
Vector's default InitialCapacity is 10.

It is a capacity of vector. Once the total elements in vector reaches to the capacity of vector it will increase its capacity. If initialCapcity is 100 then once 100 elements stored into vector it will increment capacity by 100. So, now user can add another 100 elements into Vector.

In the fourth constructor there is incrementCapacity. If the incrementCapacity is 4 then it will increment only 4 in the initialCapacity.  If initialCapcity is 100 then once 100 elements stored into vector it will increment capacity by 4.  So available new capacity is now 104 and now user can add 4 new elements into vector. after that again existing capacity will be incremented by 4. and so on...

Characteristics:
  • Vector and ArrayList has similar functionality except Vector's all methods are synchronized.
  • The data structure used for Vector class  Growable Array or Resizable Array.
  • So Vector is thread safe while ArrayList is not thread safe.
  • Vector is a resizable.  
  • It grows it size automatically once it is full.
  • It allows duplicate elements.
  • It allows null element.
  • It allows access of particular element using index value.
  • Vector has its initial capacity.
  • Size of Vector is the number elements available in the vector.
  • Capacity of the Vector grows automatically once its size reach to the capacity.
  • Vector is best choice when retrieval operation is your frequent operation in multiple threaded environment.
Example

import java.util.*;
class VectorFlight {

    public static void main(String bag[]) {
      
        Vector<String> vector = new Vector<String>();
        vector.add("A"); // method of Collection
        vector.addElement("B");// method of Vector
        vector.addElement("B"); // allows duplicate
        vector.addElement(null); // allows null      
        System.out.println(vector);      
    }
}


Output
[A, B, B, null]