Java Program to Implement Vector

What is a Vector in Java?

A vector is a dynamic data structure in Java that is similar to an array, but it is resizable and thread-safe. It is a part of the Java Collection Framework and is often used when we need to store and access a large number of elements.

In Java, vectors can be created using the Vector class, which is included in the java.util package. The Vector class provides many methods to add, remove, and retrieve elements from the vector, as well as methods to check the size and capacity of the vector. Some of the commonly used methods are add(), remove(), get(), size(), and capacity().

Vectors in Java are different from arrays in the sense that they are dynamically resizable, which means that the size of the vector can be changed at runtime. Additionally, vectors are also thread-safe, which means that they can be accessed by multiple threads without causing data inconsistency.

Problem Description

Write a Java Program to Implement Vector.

Problem Solution

How to create a Vector in Java?

advertisement
advertisement
Vector<Integer> myVector = new Vector<Integer>();

In the above syntax, we have declared a Vector that will hold integers. The <Integer> syntax specifies the type of objects that the Vector can hold. The new Vector<Integer>() syntax creates a new Vector object with an initial size of zero.

Methods Declaration:
Once you have declared a Vector, you can use its methods to add, remove, and retrieve elements. For example, you can add an element to a Vector like this:

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
myVector.add("Hello");
myVector.remove(0);
String firstElement = myVector.get(0);
  • Add elements to the Vector using the add() method.
  • Remove elements from the Vector using the remove() method.
  • Retrieve elements from the Vector using the get() method.
  • Check the size and capacity of the Vector using the size() and capacity() methods.
Program/Source Code

Here is the source code of the Java program to implement vector. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * Java program to implement vector
 */
 
import java.util.ArrayList;
import java.util.Scanner;
 
public class Vector<T> 
{
    private int capacity;
    private int size;
    private ArrayList<T> vector;
    private static final int INCREMENT_FACTOR = 5;
 
    public Vector(int size)
    {
        this.size = size;
        this.capacity = size + INCREMENT_FACTOR;
        vector = new ArrayList<T>();
    }
 
    public void store(int index, T value)
    {
        try 
        {
            vector.set(index, value);
        } catch (IndexOutOfBoundsException indexOutBounds)
        {
            if (index >= 0 && (index < size))
            {
                vector.add(index, value);
            }
            if (index >= 0 && (index >= size && index < capacity))
            {
                vector.add(index, value);
                size = index + 1;
                if (size == capacity)
                    capacity = capacity + INCREMENT_FACTOR;
            }
            if (index >= capacity)
            {
                throw new IndexOutOfBoundsException();
            }
        }
    }
 
    public T get(int index)
    {
        try
        {
            return vector.get(index);
        } catch (IndexOutOfBoundsException indexOutBounds)
        {
        }
        return null;
    }
 
    public int getSize()
    {
        return size;
    }
 
    public int getCapacity()
    {
        return capacity;
    }
 
    public static void main(String... arg)
    {
        int size;
        int num;
        int value;
 
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the initial size of the vector");
        size = scanner.nextInt();
 
        Vector<Integer> vector = new Vector<>(size);
        System.out.println("Enter the number of elements ");
        num = scanner.nextInt();
 
        System.out.println("Enter the values");
        for (int index = 0; index < num; index++)
        {
            value = scanner.nextInt();
            vector.store(index, value);
        }
 
        System.out.println("The Entered Values are");
        for (int index = 0; index < vector.getSize(); index++)
        {
            System.out.print(vector.get(index) + "\t");
        }
 
        System.out.println("\nTHE SIZE OF THE VECTOR IS  " + vector.getSize());
        System.out.println("THE CAPACITY OF THE VECTOR IS  " + vector.getCapacity());
        scanner.close();
    }
}
Program Explanation

The program is an implementation of a Vector class in Java using an ArrayList as its underlying data structure.

advertisement

The Vector class has the following attributes:

  • capacity: the current capacity of the vector
  • size: the current size of the vector
  • vector: an ArrayList object that stores the elements of the vector
  • INCREMENT_FACTOR: a constant integer value that determines how much the capacity of the vector increases when its current capacity is reached

The class also has the following methods:

  • store(int index, T value): stores the value at the specified index in the vector. If the index is out of bounds, it will add the value to the vector and adjust the capacity and size of the vector accordingly.
  • get(int index): returns the value at the specified index in the vector. If the index is out of bounds, it returns null.
  • getSize(): returns the size of the vector.
  • getCapacity(): returns the capacity of the vector.

In the main method, the user is prompted to input the initial size of the vector, the number of elements to store, and the values of the elements. The values are stored in the vector using the store method. The contents of the vector are then printed using the get method. The size and capacity of the vector are also printed using the getSize and getCapacity methods, respectively.

Runtime Test Cases
$javac Vector.java
$java Vector
 
Enter the initial size of the vector
5
Enter the number of elements 
5
Enter the values
10 9 8 7 6
The Entered Values are
10	9	8	7	6	
THE SIZE OF THE VECTOR IS  5
THE CAPACITY OF THE VECTOR IS  10

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

advertisement

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.