Let’s learn vector ensureCapacity(int minCapacity) method in java.
Vector ensureCapacity(int minCapacity) method in java
Vector ensureCapacity(int minCapacity) method increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
If the current capacity of this vector is less than minCapacity, then its capacity is increased by replacing its internal data array, kept in the field elementData, with a larger one.
The size of the new data array will be the old size plus capacityIncrement, unless the value of capacityIncrement is less than or equal to zero, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.
Syntax
public void ensureCapacity(int minCapacity)
Parameters
minCapacity – the desired minimum capacity
Example
import java.util.*; class VectorEnsureCapacityDemo { public static void main(String[] args) { Vector<Integer> v = new Vector<Integer>(6); for(int i = 0; i < 10; i++) { v.add(0, i); } System.out.println("Vector elements : " + v); System.out.println("Vector size : " + v.size()); // ensure the capacity and add elements v.ensureCapacity(30); for(int i = 0; i < 10; i++) { v.add(0, i); } System.out.println("Vector elements after increasing size : " + v); System.out.println("Vector size after increase : " + v.size()); } }
Output:
Vector elements : [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Vector size : 10
Vector elements after increasing size : [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Vector size after increase : 20
import java.util.*; class VectorEnsureCapacityDemo { public static void main(String[] args) { Vector<String> v = new Vector<>(); v.add("60"); v.add("hello"); v.add("world"); System.out.println("Vector elements : " + v); System.out.println("Vector capacity : " + v.capacity()); v.ensureCapacity(30); System.out.println("New Vector capcity : " + v.capacity()); } }
Output:
Vector elements : [60, hello, world]
Vector capacity : 10
New Vector capcity : 30
Also read – HashSet in java