Monday, 5 May 2014

public Vector(int initialCapacity, int capacityIncrement)

public Vector(int initialCapacity, int capacityIncrement)
Constructs an empty vector with the specified initial capacity and capacity increment.

import java.util.*;
class VectorConstructor3{
 public static void main(String args[]){
  Vector<Integer> myVector = new Vector<> (4, 3);
  
  System.out.print("Size of myVector is ");
  System.out.println(myVector.size());
  System.out.print("Capacity of myVector is ");
  System.out.println(myVector.capacity());
  
  /*Adding Elements to Vector */
  System.out.println("\nAdd 5 Elements to myVector");
  myVector.add(10);
  myVector.add(20);
  myVector.add(30);
  myVector.add(40);
  myVector.add(50);
  
  System.out.print("\nSize of myVector is ");
  System.out.println(myVector.size());
  System.out.print("Capacity of myVector is ");
  System.out.println(myVector.capacity());
 }
}

Output
Size of myVector is 0
Capacity of myVector is 4

Add 5 Elements to myVector

Size of myVector is 5
Capacity of myVector is 7


As you observe the program, initialCapacity is set to 4 and capacityIncrement is set to 3. So Whenever the Size goes beyond the capacity, then the capacity is incremented with the value of capacityIncrement. Here Capacity 4 becomes 7(4+3).

1.throws IllegalArgumentException if the specified initial capacity is negative
import java.util.*;
class VectorConstructor3Illegal{
 public static void main(String args[]){
  Vector<Integer> myVector = new Vector<> (-1, 3);
 }
}


Output
Exception in thread "main" java.lang.IllegalArgumentException: Illegal Capacity:-1
        at java.util.Vector.<init>(Vector.java:129)
        at VectorConstructor3Illegal.main(VectorConstructor3Illegal.java:4)

2. If capacityIncrement is less than or equal to zero, then the capacity will be doubled whenever the Size goes beyond the capacity.
import java.util.*;
class VectorConstructor3Ex{
 public static void main(String args[]){
  Vector<Integer> myVector = new Vector<> (4, 0);
  
  System.out.print("Size of myVector is ");
  System.out.println(myVector.size());
  System.out.print("Capacity of myVector is ");
  System.out.println(myVector.capacity());
  
  /*Adding Elements to Vector */
  System.out.println("\nAdd 5 Elements to myVector");
  myVector.add(10);
  myVector.add(20);
  myVector.add(30);
  myVector.add(40);
  myVector.add(50);
  
  System.out.print("\nSize of myVector is ");
  System.out.println(myVector.size());
  System.out.print("Capacity of myVector is ");
  System.out.println(myVector.capacity());
 }
}

Output
Size of myVector is 0
Capacity of myVector is 4

Add 5 Elements to myVector

Size of myVector is 5
Capacity of myVector is 8


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment