Open In App

How to Initialize a Vector with a Specific Initial Capacity in Java?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Vector Class allows to creation of dynamic arrays that can grow or shrink as per the need. If we know the approximate size of elements, we will store this in the vector. Then we optimize memory usage, and we can initialize it with the specific initial capacity.

In this article, we will learn how to initialize a Vector with a specific initial capacity in Java.

Example Input-Output:

Input: int initialCapacity = 10;Vector<String> string
Vector = new Vector<>(initialCapacity);

Output: A Vector named stringVector is created with the initial capacity of 10.

Syntax:

Vector<E> vector = new Vector<>(initialCapacity);
  • E: The type of elements in Vector.
  • initialCapacity: The initial capacity of the Vector. It represents the number of elements the Vector can initially store without the resizing.

Program to Initialize a Vector with Initial Capacity in Java

Below is the implementation to Initialize a Vector with Initial Capacity:

Java




// Java program to initialize a 
// Vector with a specific initial capacity
import java.io.*;
import java.util.Vector;
  
// Driver Class
public class GFG {
    // Main Function
    public static void main(String[] args) {
        // Initializing a Vector with
        // the specific initial capacity
        int Capacity = 10;
        Vector<String> stringVector = new Vector<>(Capacity);
          
        // Adding elements to Vector
        stringVector.add("Java");
        stringVector.add("is");
        stringVector.add("powerful.");
          
        // Displaying the elements of the Vector
        System.out.println("The Vector elements: " + stringVector);
    }
}


Output

The Vector elements: [Java, is, powerful.]

Explanation of the Program:

In the above program,

  • Initialization: The initial capacity is set to 10. A Vector named stringVector is created with this initial capacity.
  • Adding Elements: Three string elements are added to stringVector.
  • Displaying Elements: The elements of stringVector are printed to console.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads