In the previous article, we have discussed about Java Vector capacity( ) Method with Example
In this article, we are going to see the use of Java Vector ensureCapacity() method along with examples.
Java Vector ensureCapacity( ) Method with Example
ThisĀ java.util.Vector.ensureCapacity() method ensures that the vector can hold a minimum number of elements passed to the method as a minimum capacity argument. It increases the size of the vector. Its return type is void.
Syntax:
vectorName.ensureCapacity(int minimum_req_capacity);
Where,
vectorNamerefers to the name of the Vector.minimum_req_capacityrefers to the parameter passed to the method which sets the minimum capacity required in the vector.
Approach:
- Create a vector of string data type and add some elements to it.
- Print the elements.
- Set the capacity of the vector to 20 by passing it to
ensureCapacity( )method. - Now print the new capacity of the vector.
Program:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Create a Vector of string datatype
Vector<String> vec = new Vector<String>();
// Adding some elements to the vector
vec.add("One");
vec.add("Two");
vec.add("Three");
vec.add("Four");
vec.add("Five");
vec.add("Six");
vec.add("Seven");
// Prints the vector elements
System.out.println("The vector elements are "+vec);
// Prints the capacity of the vector
System.out.println("The capacity of the vector is "+vec.capacity());
// increases the capacity to 20
vec.ensureCapacity(20);
// Prints the new capacity of the vector
System.out.println("The new capacity of the vector is "+vec.capacity());
}
}
Output: The vector elements are [One, Two, Three, Four, Five, Six, Seven] The capacity of the vector is 10 The new capacity of the vector is 20
Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples.
Related Java Programs: