How to Initialize a Vector with a Specific Initial Capacity in Java?
Last Updated :
12 Feb, 2024
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
import java.io.*;
import java.util.Vector;
public class GFG {
public static void main(String[] args) {
int Capacity = 10 ;
Vector<String> stringVector = new Vector<>(Capacity);
stringVector.add( "Java" );
stringVector.add( "is" );
stringVector.add( "powerful." );
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.
Share your thoughts in the comments
Please Login to comment...