What Is Java Vector | Java Vector Class Tutorial With Examples

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated September 12, 2024

This Tutorial Explains all about Vector Data Structure in Java With Examples. You will learn to Create, Initial, Sort & Use A Java Vector in your Programs:

A vector can be defined as a dynamic array that can grow or shrink on its own i.e. vector will grow when more elements are added to it and will shrink when elements are removed from it.

This behavior is unlike that of arrays which are static. But similar to arrays, vector elements can be accessed using integer indices.

=> Check Here To See A-Z Of Java Training Tutorials Here.

Vectors in Java

A vector can be viewed as similar to another dynamic array data structure, ArrayList except for the two below differences:

  • The vector is synchronized i.e. all the methods in Vector are marked ‘synchronized’ and thus once a method is invoked, the same method cannot be invoked unless the previous call has ended.
  • The vector class has many methods that are not a part of the collections framework but its legacy methods.

Java Vector Class

A Vector class is apart of the “java.util” package and implements List interface. A Vector is an array of objects or vector of objects.

A class declaration of Vector class is given below:

public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable

As shown above, a Vector class extends “java.lang.object” and implements List, Cloneable and Serializable interfaces.

How To Create A Vector In Java?

You can create a Vector object using any of the following Vector constructor methods.

Constructor PrototypeDescription
vector()This is the default constructor of the Vector class. It creates an empty vector with size 10.
vector(int initialCapacity)This overloaded constructor constructs an empty Vector object with the capacity = initialCapacity.
vector(int initialCapacity, int capacityIncrement)This constructor method creates an empty Vector object with specified initialCapacity and capacityIncrement.
Vector( Collection< ? extends E> c)A Vector object is created with the initial elements from specified collection c.

Let’s look at each of the constructors to initialize Vector objects.

Initialize Vector

(i) Vector()

This is the default constructor of the Vector class. When you invoke this constructor, a Vector object of default size 10 is created.

The general syntax of this method is:

Vector object = new Vector();

For Example,

Vector vec1 = new Vector ();

The above statement creates a new Vector ‘vec1’ with size 10.

(ii) Vector(int initialCapacity)

The overloaded constructor of the Vector class accepts ‘initialCapacity’ as the argument. This constructor creates a Vector object with the specified capacity.

The general syntax of the method is:

Vector object = new Vector (initialCapacity);

For Example,

Vector vec1 = new Vector (10);

The above programming statement will create a Vector object ‘vec1’ with the capacity of 10 i.e. this Vector can store up to 10 elements.

(iii) Vector(int initialCapacity, int capacityIncrement)

This is yet another overloaded constructor of Vector class and it creates a Vector object with the specified initial capacity and increment for the capacity.

The general syntax for this method is:

Vector object = new Vector (initialCapacity, capacityIncrement);

For Example,

Vector vec1 = new Vector(5,10);

In the above statement, the initial capacity of the Vector is 5 and increment is 10. This means when the 6th element is inserted into the vector, the capacity of the vector will be incremented to 15 (5 + 10). Similarly, when the 16th element is inserted, the vector capacity of the Vector will be extended to 25 (15 +10).

(iv) Vector(Collection<? extends E> c)

The last overloaded constructor of the Vector class takes in a predefined collection as an argument and creates a Vector with all the elements from this collection as its elements.

The general syntax is:

Vector object = new Vector (Collection<? extends E> c);

For Example,

Vector vec1 = new Vector(aList); where aList = {1,2,3,4,5};

The above statement will create a Vector ‘vec1’ with initial elements as {1,2,3,4, 5}.

Keeping all these descriptions in mind will let us implement a Vector program to understand these constructors better.

Vector Methods In Java

The following are the methods that are supported by Vector class in Java.

Method NamePrototypeDescription
addBoolean add(E e)Adds given element to the end of the vector.
Void add(int index, E element)Add element to the vector at the specified index.
addAllBoolean addAll(Collection< ? extends E> c)Adds all the elements from given collection to the end of vector.
Boolean addAll(int index, Collection< ? extends E> c)Adds all the elements in the specified collection at specified index.
addElementvoid addElement(E obj)Adds the specified element at the end of the vector by increasing the vector size.
CapacityInt capacity()Returns current capacity of the vector.
ClearVoid clear()Clears the vector of its elements.
CloneObject clone()Clones the vector.
ContainsBoolean contains(Object o)Checks if the vector contains specified element.
containsAllBoolean containsAll(Collection< ?> c)Checks if the vector contains all the elements present in given collection.
copyIntoVoid copyInto(Object[] anArray)Copies the vector elements into given array.
ElementAtE ElementAt(int index)Returns vector element at specified index.
ElementsEnumeration< E>elements()Returns enumerated components for the vector.
ensureCapacityVoid ensureCapacity(int minCapacity)Increases the capacity of vector to meet the minimum capacity specified.
Method NamePrototypeDescription
EqualsBoolean equals(Object o)Compares current vector with specified vector to check if they are equal.
firstElementE firstElement()Returns the first element of the vector at index 0.
GetE get(int index)Returns the element in the vector at the specified index.
hashCodeint hashCode()Returns the hash code value for the Vector.
indexOfint indexOf(Object o)finds the index of the first occurrence of the given element in the vector; -1 if element is not present in the vector.
int indexOf(Object o, int index)Searches the vector from the given index in forward direction for specified element;returns index if element is found else -1 if the element is not found.
insertElementAtVoid insertElementAt(E obj, int index)Inserts the given object in the vector at the given index.
isEmptyBoolean isEmpty()Checks if the vector is empty.
IteratorIterator< E>iterator()Returns an iterator that is used to traverse over the elements of the vector.
lastElementE lastElement()Returns the last element of the vector.
lastIndexOfInt lastIndexOf(Object o)Searches the vector for the last occurrence of given element and returns the index, or returns -1 the element is not found.
Int lastIndexOf(Object o, int index)Starts searching for last occurrence of the given element from the given index backwards. Returns the index if element is found else returns -1.
listIteratorListIterator< E>listIterator()Returns a list iterator over the vector elements.
ListIterator< E>listIterator(int index)Returns a list iterator over the vector elements starting from the given index.
Method NamePrototypeDescription
RemoveE remove(int index)Deletes element at given index from the vector.
Boolean remove(Object o)Deletes first occurrence of the given element from the vector. If element is not present, nothing happens to the vector
removeAllBoolean removeAll(Collection< ?> c)Deletes all the elements from the vector that are present in the given collection.
void removeAll Elements()Deletes all vector elements thus reducing it to size zero.
removeElementBoolean removeElement(Object obj)Removes the first occurrence of the given element from the vector.
void removeElementAt(int index)Deletes the element at the given index.
removeRangeprotected void removeRange(int fromIndex, int toIndex)Deletes all the elements from the vector in the given range from fromIndex (inclusive), totoIndex (exclusive).
retainAllBoolean retainAll(Collection< ?> c)As opposed to ‘removeAll’ the method retainAll retains elements in the Vector that match to elements in specified Collection.
setE set(int index, E element)Sets the value at given index with the new element provided.
Void set ElementAt(E obj, int index)Sets the given elements at the given index.
setSizeVoid setSize(int newSize)Sets given size for this vector.
Sizeint size()Returns the number of elements in this vector or the length of the vector.
subListList< E>subList(intfromIndex, inttoIndex)Returns a view or subList of the vector ranging from fromIndex to toIndex.
toArrayObject[] toArray()Converts the given vector into an array containing all vector elements in given order.
< T> T[] toArray(T[] a)Returns an array of type specified containing all vector elements.
toStringString toString()Returns a string representation of the vector.
trimToSizevoid trimToSize()Trims the vector to accommodate the current size.

Vector Implementation

The following Java program demonstrates the usage of all the constructor methods described above.

import java.util.*;
public class Main{
    public static void main(String[] args)  {
        //Create vectors v1, v2,v3 and v4
        Vector v1 = new Vector();  //a vector with default constructor
        Vector v2 = new Vector(20);  // a vector of given Size
        //initialize vector v2 with values
        v2.add(10);
        v2.add(20);
        v2.add(30);
        Vector v3 = new Vector(30, 10); // a vector of given Size and Increment
         // create a vector v4 with given collection
        List&amp;amp;lt;String&amp;amp;gt; aList = new ArrayList&amp;amp;lt;&amp;amp;gt;();
        aList.add(&amp;amp;quot;one&amp;amp;quot;);
        aList.add(&amp;amp;quot;two&amp;amp;quot;);
        Vector v4 = new Vector(aList);
        //print contents of each vector
       System.out.println(&amp;amp;quot;Vector v1 Contents:&amp;amp;quot; + v1);
       System.out.println(&amp;amp;quot;Vector v2 Contents:&amp;amp;quot; + v2);
       System.out.println(&amp;amp;quot;Vector v3 Contents:&amp;amp;quot; + v3);
       System.out.println(&amp;amp;quot;Vector v4 Contents:&amp;amp;quot; + v4);
    }
}

Output:

Vector Implementation

The above program has four Vectors in it. The first v1 is created with a default constructor. The second Vector v2 is created with initial capacity as 20. Then few elements are added to v2. The third Vector is created with an initial capacity of 30 and increment 10.

Next, we create an ArrayList and create a fourth Vector v4 with the ArrayList as its argument. Finally, we display the contents of each of these Vectors.

Note the contents of the fourth Vector v4. As we have provided ArrayList as its argument, the contents of ArrayList become the contents of v4.

Complete Vector Example

Now let’s implement yet another program that will demonstrate the creation of vectors, adding elements to it and displaying its contents.

import java.util.*;
public class Main {
        public static void main(String args[]) {
        //Create an empty Vector of even numbers
        Vector &amp;amp;lt; Integer &amp;amp;gt; evenVector= new Vector &amp;amp;lt;&amp;amp;gt; ();
          //Add elements in the vector
        evenVector.add(2);
        evenVector.add(4);
        evenVector.add(6);
        evenVector.add(8);
        evenVector.add(10);
        evenVector.add(12);
        evenVector.add(14);
        evenVector.add(16);
        //Display the vector
        System.out.println(&amp;amp;quot;Vector evenVector contents: &amp;amp;quot; +evenVector);
        //delete the first occurence of an element 4 using remove method
        System.out.println(&amp;amp;quot;\nFirstoccurence of element 4 removed: &amp;amp;quot;+evenVector.remove((Integer)4));
        //Display the vector
       System.out.println(&amp;amp;quot;\nVector contents after remove operation: &amp;amp;quot; +evenVector);
        //Remove the element at index 4 &amp;amp;amp; display the vector
        System.out.println(&amp;amp;quot;\nRemove element at index 4: &amp;amp;quot; +evenVector.remove(4));
        System.out.println(&amp;amp;quot;\nVector contents after remove: &amp;amp;quot; +evenVector);
        //hashcode for the vector
        System.out.println(&amp;amp;quot;\nHash code of the vector = &amp;amp;quot;+evenVector.hashCode());
        //Get the element at index 1
         System.out.println(&amp;amp;quot;\nElement at index 1 is = &amp;amp;quot;+evenVector.get(1));
          }
}

Output:

Complete Vector example

Let’s take another vector example. In this program, we will use a string vector. We manipulate this vector by adding elements and then print its size and capacity.

import java.util.*;

public class Main {
   public static void main(String args[]) {
      // create a vector with initial capacity = 2
      Vector&amp;amp;lt;String&amp;amp;gt; fruits_vec = new Vector&amp;amp;lt;String&amp;amp;gt;(2);

      //add elements to the vector
     fruits_vec.addElement(&amp;amp;quot;Grapes&amp;amp;quot;);
     fruits_vec.addElement(&amp;amp;quot;Melon&amp;amp;quot;);
     fruits_vec.addElement(&amp;amp;quot;Kiwi&amp;amp;quot;);
     fruits_vec.addElement(&amp;amp;quot;Apple&amp;amp;quot;);
      //print current size and capacity of the vector
     System.out.println(&amp;amp;quot;Vector Size: &amp;amp;quot;+fruits_vec.size());
     System.out.println(&amp;amp;quot;Default Vector capacity increment: &amp;amp;quot;+fruits_vec.capacity());
       //add more elements to the vector
      fruits_vec.addElement(&amp;amp;quot;Orange&amp;amp;quot;);
      fruits_vec.addElement(&amp;amp;quot;Mango&amp;amp;quot;);
      fruits_vec.addElement(&amp;amp;quot;Fig&amp;amp;quot;);

      //print current size and capacity again
      System.out.println(&amp;amp;quot;Vector Size after addition: &amp;amp;quot;+fruits_vec.size());
      System.out.println(&amp;amp;quot;Vector Capacity after increment: &amp;amp;quot;+fruits_vec.capacity());

      //print vector elements
      Enumeration fruits_enum = fruits_vec.elements();
      System.out.println(&amp;amp;quot;\nVector Elements are:&amp;amp;quot;);
      while(fruits_enum.hasMoreElements())
       System.out.print(fruits_enum.nextElement() + &amp;amp;quot; &amp;amp;quot;);
   }
}

Output:

Use string vector

Sort A Vector

You can also sort a vector according to a specific order. For sorting a Vector, you have to use the Collections.sort () method of Java Collections Framework.

The following example shows vector sorting.

import java.util.*;
public class Main {
    public static void main(String arg[]) {
        //Create an empty vector
        Vector&amp;amp;lt;Integer&amp;amp;gt; oddVector = new Vector&amp;amp;lt;&amp;amp;gt;();
        //Add elements to the vector
        oddVector.add(1);
        oddVector.add(11);
        oddVector.add(7);
        oddVector.add(3);
        oddVector.add(5);
        //print the vector elements
        System.out.println(&amp;amp;quot;Vector elements: &amp;amp;quot;+oddVector);
        //sort vector using Collections.sort method
        Collections.sort(oddVector);
        //print sorted vector
       System.out.println(&amp;amp;quot;Vector elements after sorting: &amp;amp;quot;+oddVector);
    }
}  

Output:

Sort a Vector

The above program creates a Vector of odd numbers. Then using the Collections.sort() method, the Vector is sorted.

2D (Two-dimensional) Vector

A 2d Vector is a Vector that has each of its elements as a Vector. It can also be termed as ‘Vector of Vectors’.

An example below demonstrates the 2d Vector.

import java.util.*;

public class Main {
   public static void main(String args[]) {
    //define and initialize a vector
    Vector inner_vec = new Vector();
    inner_vec.add(&amp;amp;quot;Software&amp;amp;quot;);
    inner_vec.add(&amp;amp;quot;Testing&amp;amp;quot;);
    inner_vec.add(&amp;amp;quot;Java&amp;amp;quot;);
    inner_vec.add(&amp;amp;quot;Tutorials&amp;amp;quot;);

    //define another vector and add first vector to it.
    Vector outer_vec = new Vector();
    outer_vec.add(inner_vec);
    String str;
    //display the contents of vector of vectors
    System.out.println(&amp;amp;quot;Contents of vector of vectors:&amp;amp;quot;);
    for(int i=0;i&amp;amp;lt;inner_vec.size();i++){
        str = (String) ((Vector) outer_vec.get(0)).get(i);
        System.out.print(str + &amp;amp;quot; &amp;amp;quot;);
    }
  }

Output:

2D (two-dimensional) Vector

In the above program, we have a Vector of four elements. Then, we declare another vector and add the previous vector as an element to the second vector. Note the way the elements of the vector is accessed. Form the for loop, you can conclude that the outer vector’s first element (at index 0) is the first or inner vector.

Thus, in the loop, we keep the index of the outer vector as 0 and loop through the inner vector to display all the elements.

Convert Vector To Array

Let’s consider the following example of converting a Vector to an array. To convert a Vector to an Array, we make use of the ‘toArray’ method of the Vector class.

In the following programming example, we declare a string Vector and add elements to it. Then using the toArray method of the Vector class, we convert the Vector to a String array by passing the string array object as an argument.

import java.util.Vector;

public class Main {
   public static void main(String[] args) {
      // Create a Vector of String elements
     Vector&amp;amp;lt;String&amp;amp;gt; color_vector = new Vector&amp;amp;lt;String&amp;amp;gt;();

     // Add elements to Vector
     color_vector.add(&amp;amp;quot;Violet&amp;amp;quot;);
     color_vector.add(&amp;amp;quot;Indigo&amp;amp;quot;);
     color_vector.add(&amp;amp;quot;Blue&amp;amp;quot;);
     color_vector.add(&amp;amp;quot;Green&amp;amp;quot;);
     color_vector.add(&amp;amp;quot;Yellow&amp;amp;quot;);
     color_vector.add(&amp;amp;quot;Orange&amp;amp;quot;);
     color_vector.add(&amp;amp;quot;Red&amp;amp;quot;);

    //Convert Vector to String Array using toArray method
   String[] colorsArray = color_vector.toArray(new String[color_vector.size()]);

    //print Array Elements
   System.out.println(&amp;amp;quot;String Array Elements :&amp;amp;quot;);
   for(String val:colorsArray){
      System.out.print(val + &amp;amp;quot; &amp;amp;quot;);
    }
  }
}

Output:

Convert vector to array

Vector vs Array

Enlisted below are some of the differences between a Vector and an Array.

VectorArray
Vector is dynamic and its size grows and shrinks as elements are added or removed.Arrays are static and its size remains fixed once declared.
Vectors can store only objects.Arrays can store primitive types as well as objects.
It provides a size() method to determine the size.Provides length property to determine the length.
No concept dimensions but can be created as a vector of vectors, normally called 2d vector.Arrays support dimensions.
Vector is synchronized.The array is not synchronized.
Vector is slower than the array.Array is faster.
Reserves additional storage when capacity is incremented.Does not reserve any additional storage.
Ensures type safety by supporting generics.No generic support.

Vector vs ArrayList

This section discusses the difference between Vector and ArrayList in Java.

VectorArrayList
Present since the initial version of Java(JDK 1.0 version).Introduced in Java since JDK 1.2
Vector is a legacy class of Java.ArrayList is a part of the Java Collections Framework.
Vector grows double its size when its capacity is reached.ArrayList grows by half the size when its capacity is reached.
Vector methods are synchronized.ArrayList is not synchronized.
Vector uses Enumerator and Iterator for traversing.ArrayList uses only Iterator.
Vector operations are slower.ArrayList is faster.
Vector has increment size using which vector size can be increased.ArrayList does not provide increment size.
Vector is thread-safe which means using Vector from multiple threads is permitted and is safe.ArrayList is not thread-safe.

Frequently Asked Questions

What is a Vector in Java?

In Java, a Vector can be defined as a growable array of objects. Similar to arrays, Vector elements can also be accessed using indices.

Is vector ordered in Java?

Yes. A Vector is ordered and maintains the inserting order for elements.

Is Vector thread-safe in Java?

Yes. In Java the Vector class is thread-safe. As the Vector class is synchronized, it makes it thread-safe i.e. you can use the Vector class from multiple threads and it is safe.

Why do we use vectors in Java?

The most important reason for which Vector is used in Java is that a Vector grows and shrinks automatically. They are dynamic because of which they are preferred over arrays.

Which is better – ArrayList or vector?

Performance-wise ArrayList is faster when compared to Vector as Vector is synchronized and makes it slower.


Conclusion

In this tutorial, we started with the Vector data structure in Java. Vectors are almost similar to an array in which the Vector elements are accessed using familiar indices. Vectors are called dynamic array and unlike arrays, the Vector size grows and shrinks automatically.

Vectors also have the capacity and increment features that can be used to create and reserve additional storage for future additions. Vector is a legacy class in java.util package of Java and is synchronized as well as thread-safe.

Thus, we should prefer vectors when we need dynamic size and also while we are working in a multi-threaded environment.

=> Visit Here For The Exclusive Java Training Tutorial Series.

Was this helpful?

Thanks for your feedback!

Leave a Comment