Vector Class In Java

Vector Class In Java: A Vector also stores elements (objects) similar to ArrayList, but the vector is synchronized. It means the results will be reliable even if several threads simultaneously act on the Vector object.

As Vector is synchronized, it is rarely used in the non-thread environment because it will perform poorly in operations like searching, adding, deleting, and updating its elements.

The implemented data structure of Vector is a growable array. Vector is one type of legacy class (Those classes come from the earlier or first version of Java and have not been modified), but now it is fully compatible with collections.

Important Points to Remember Of Vector

  • The underlying data structure is a resizeable Array or growable array, which means it can grow or shrink as expected.
  • You can access the vector elements using the index like in an array.
  • There are many similarities between ArrayList and Vector, but the vector is synchronized; hence, the vector elements are thread-safe.
  • Insertion order is preserved.
  • Duplicates are allowed
  • Heterogeneous elements are allowed.
  • Null Insertion is possible.
  • It implements Serializable, Cloneable, and Random Access interfaces.

Different Way to Create Vector Class object

Vector vec = new Vector();

This will create an empty vector with an initial capacity of 10, which means you can insert ten elements, and when you try to insert the 11th element vector, it automatically doubles its size by 20.

Vector object= new Vector(int initialCapacity);

If you try to initialize the vector with some initial capacity, then you can use the above syntax, and according to the above syntax, it will create a vector object with the mentioned initial capacity.

Vector object= new vector(int initialcapacity, capacityIncrement);

If you are going to create a vector class object by using the above syntax and with two parameters like initialCapacity and capacity increment, that means once the insert element number reaches the initial capacity number, then the capacity increment will not double; it will increment only as of the capacity increment mentioned value.

Vector vec= new Vector(2, 5);

That means when you enter the 3rd number variable, the vector size increases by 5, so the total size of the vector after increment is 7 (2+5).

Vector Constructor

Like other collection classes, Vector also has constructors, and that is:

  • Vector(): Creates a default vector of the initial capacity 10.
  • Vector(int size): Creates a vector whose initial capacity is specified by size.
  • Vector(Collection c): A vector containing the collection c elements is created.
  • Vector( Collection<? extends E> c): It constructs a vector containing a collection of c’s elements.
  • Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and increment is specified by incr. It specifies the number of elements allocating each time a vector is resized upward.

Note: If the increment is specified, then the vector will expand according to the mentioned size on each allocation cycle, but if the increment is not specified, then the vector capacity gets doubled in each allocation cycle.

Vector Methods

Add the different Vector Methods with Example

Vector Program Example

Write a Program to Add Elements in Vector and Retrieve Using Enumeration.

package com.java.Softwaretestingblog;
import java.util.Enumeration;
import java.util.Vector;
public class VectorEnnumaration {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Vector<String> vct = new Vector<String>();
      //adding elements to the end
      vct.add("First");
      vct.add("Second");
      vct.add("Third");
      vct.add("Random");
      Enumeration<String> enm = vct.elements();
      while(enm.hasMoreElements())
      {
         System.out.println(enm.nextElement());
      }
   }
}

Output:

First
Second
Third
Random

Write A Program to Add and retrieve Vector Elements.

package com.java.Softwaretestingblog;
import java.util.Iterator;
import java.util.Vector;
public class VectorIterator {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Vector<String> vct = new Vector<String>();
      //adding elements to the end
      vct.add("First");
      vct.add("Second");
      vct.add("Third");
      vct.add("Random");
      Iterator<String> itr = vct.iterator();
      while(itr.hasNext())
      {
         System.out.println(itr.next());
      }
   }
}

Output:

First
Second
Third
Random

Write a Program For Basic Vector Operations In Java With Program?

package com.java.Softwaretestingblog;
import java.util.Vector;
public class BasicVectorOperations {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Vector<String> vct = new Vector<String>();
      //adding elements to the end
      vct.add("First");
      vct.add("Second");
      vct.add("Third");
      System.out.println(vct);
      //adding element at specified index
      vct.add(2,"Random");
      System.out.println(vct);
      //getting elements by index
      System.out.println("Element at index 3 is: "+vct.get(3));
      //getting first element
      System.out.println("The first element of this vector is: "+vct.firstElement());
      //getting last element
      System.out.println("The last element of this vector is: "+vct.lastElement());
      //how to check vector is empty or not
      System.out.println("Is this vector empty? "+vct.isEmpty());
   }
}

Output:

[First, Second, Third]
[First, Second, Random, Third]
Element at index 3 is: Third
The first element of this vector is: First
The last element of this vector is: Third
Is this vector empty? false

Write a Program to Retrieve Vector Elements Using Enumeration.

package com.java.Softwaretestingblog;
import java.util.Enumeration;
import java.util.Vector;
public class MyEnumeration {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Vector<String> lang = new Vector<String>();
       Enumeration<String> en = null;
        lang.add("JAVA");
        lang.add("JSP");
        lang.add("SERVLET");
        lang.add("EJB");
        lang.add("PHP");
        lang.add("PERL");
        en = lang.elements();
        while(en.hasMoreElements())
        {
            System.out.println(en.nextElement());
        }
   }
}

Output:

Java
Unix
Oracle
C++
Perl

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment