Java

How To Use Vector In Java?

List Interface is implemented by Vector. As with ArrayList, it also preserves insertion order, but since it is synchronized, it performs poorly while searching for, adding, deleting, and updating its items. As a result, it is seldom used in non-thread environments.

Three ways to create vector class object:

Method 1:

Vector vec = new Vector();

It generates a new Vector that is empty and has a preset starting size of 10. It indicates that the Vector will be resized when the 11th element has to be added. Note: The size of a vector is by default doubled. i.e. In this scenario, the vector size would continue at 10 up until the 10th insertion, at which point it would increase to 20. (double of default capacity 10).

Method 2:
Syntax: Vector object= new Vector(int initialCapacity)

Vector vec = new Vector(3);

It will produce a Vector with a 3-unit starting capacity.

Method 3:
Syntax:

Vector object= new vector(int initialcapacity, capacityIncrement)

Example:

Vector vec= new Vector(4, 6)

Here, we’ve presented two justifications. 4 is the original capacity, while 6 is the capacityIncrement. It indicates that the size would be 10 (4+6) with addition of the fifth element and 16 (10+6) upon insertion of the eleventh.

Complete Example of Vector in Java:

import java.util.*;

public class VectorExample {

   public static void main(String args[]) {
      /* Vector of initial capacity(size) of 2 */
      Vector<String> vec = new Vector<String>(2);

      /* Adding elements to a vector*/
      vec.addElement("Apple");
      vec.addElement("Orange");
      vec.addElement("Mango");
      vec.addElement("Fig");

      /* check size and capacityIncrement*/
      System.out.println("Size is: "+vec.size());
      System.out.println("Default capacity increment is: "+vec.capacity());

      vec.addElement("fruit1");
      vec.addElement("fruit2");
      vec.addElement("fruit3");

      /*size and capacityIncrement after two insertions*/
      System.out.println("Size after addition: "+vec.size());
      System.out.println("Capacity after increment is: "+vec.capacity());

      /*Display Vector elements*/
      Enumeration en = vec.elements();
      System.out.println("\nElements are:");
      while(en.hasMoreElements())
         System.out.print(en.nextElement() + " ");
   }
}

Output:

Size is: 4
Default capacity increment is: 4
Size after addition: 7
Capacity after increment is: 8

Elements are:
Apple Orange Mango Fig fruit1 fruit2 fruit3

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button