The ensureCapacity() method of Java.util.Vector class increases the capacity of this Vector instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
Syntax:
public void ensureCapacity(int minCapacity)
Parameters: This method takes the desired minimum capacity as a parameter.
Below are the examples to illustrate the ensureCapacity() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Vector<Integer>
vector = new Vector<Integer>();
vector.add( 10 );
vector.add( 20 );
vector.add( 30 );
vector.add( 40 );
System.out.println( "Vector: "
+ vector);
vector.ensureCapacity( 5000 );
System.out.println( "Vector can now"
+ " surely store upto"
+ " 5000 elements." );
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
Vector: [10, 20, 30, 40]
Vector can now surely store upto 5000 elements.
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Vector<String>
vector = new Vector<String>();
vector.add( "A" );
vector.add( "B" );
vector.add( "C" );
vector.add( "D" );
System.out.println( "Vector: "
+ vector);
vector.ensureCapacity( 400 );
System.out.println( "Vector can now"
+ " surely store upto"
+ " 400 elements." );
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
Vector: [A, B, C, D]
Vector can now surely store upto 400 elements.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
24 Dec, 2018
Like Article
Save Article