Tuesday 6 May 2014

Vector : ensureCapacity

public synchronized void ensureCapacity(int minCapacity)
Increases the capacity of this vector.

If currentCapacity is less than minCapacity, then current Capacity is incremented with capacityIncrement if capacityIncrement >0 else doubled, I.e,

currentCapacity =currentCapacity+ capacityIncrement(if capacityIncrement >0)
                        = 2* currentCapacity (else)

if the newly calculated currentCapacity is less than minCapacity, then currentCapacity is set to minCapacity.

import java.util.*;

class VectorEnsureCapacity{
 public static void main(String args[]){
  Vector<String> myVector;
  myVector = new Vector<> (5, 4);
  
  /* Add Elements to myVector */
  for(int i=1; i<6; i++)
   myVector.add("String " +i); 
   
  System.out.println("Capacity Of myVector is");
  System.out.println(myVector.capacity());
  
  System.out.println("\nSetting Capacity of vector to 10");
  myVector.ensureCapacity(10);
  System.out.println("Capacity Of myVector is");  
  System.out.println(myVector.capacity());
  
  System.out.println("\nSetting Capacity of vector to 11");
  myVector.ensureCapacity(11);
  System.out.println("Capacity Of myVector is");
  System.out.println(myVector.capacity());
 }
}

Output
Capacity Of myVector is
5

Setting Capacity of vector to 10
Capacity Of myVector is
10

Setting Capacity of vector to 11
Capacity Of myVector is
14

As you observe the output, Program sets the capacity to 11, but capacity() returns 14.

currentCapacity is less than minCapacity, then current Capacity is incremented with capacityIncrement

currentCapacity = currentCapacity + capacityIncrement
                        = 10 + 4
                        = 14

if the newly calculated currentCapacity is less than minCapacity, then currentCapacity is set to minCapacity. Here currentCapacity is 14 which is greater than minCapacity 11, So currentCapacity set to 14.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment