Friday 9 May 2014

Vector : setSize : Set the Size of the vector

public synchronized void setSize(int newSize)
Sets the size of this vector. If the new size is greater than the current size, new null items are added to the end of the vector. If the new size is less than the current size, all components at index newSize and greater are discarded.

import java.util.*;

class VectorSetSize{
 public static void main(String args[]){
  Vector<Integer> myVector; 
  myVector = new Vector<> ();

  /*Add Elements to myVector*/
  myVector.add(10);
  myVector.add(11);
  myVector.add(12);
  myVector.add(13);
  
  System.out.println("Elements in myVector ");
  System.out.println(myVector);
  System.out.print("Currnet size of myVector is ");
  System.out.println(myVector.size());
  
  System.out.println("\nSet size to 10");
  myVector.setSize(10);
  System.out.println("Elements in myVector ");
  System.out.println(myVector);
  
  
  System.out.println("\nSet size to 2");
  myVector.setSize(2);
  System.out.println("Elements in myVector ");
  System.out.println(myVector);
 }
}

Output
Elements in myVector
[10, 11, 12, 13]
Currnet size of myVector is 4

Set size to 10
Elements in myVector
[10, 11, 12, 13, null, null, null, null, null, null]

Set size to 2
Elements in myVector
[10, 11]

1. Throws ArrayIndexOutOfBoundsException if the new size is negative
import java.util.*;

class VectorSetSizeIndexOut{
 public static void main(String args[]){
  Vector<Integer> myVector; 
  myVector = new Vector<> ();
  
  System.out.println("Set size to -1");
  myVector.setSize(-1);
 }
}

Output
Set size to -1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at java.util.Vector.setSize(Vector.java:288)
        at VectorSetSizeIndexOut.main(VectorSetSizeIndexOut.java:9)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment