java.util.Vector.setSize() Method

Advertisements


Description

The setSize(int newSize) method is used to set 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.

Declaration

Following is the declaration for java.util.Vector.setSize() method

public void setSize(int newSize)

Parameters

  • newSize--This is the new size of the vector

Return Value

NA

Exception

  • ArrayIndexOutOfBoundsException--This exception is thrown if the new size is negative.

Example

The following example shows the usage of java.util.Vector.setSize() method.

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {
      // create an empty Vector vec with an initial capacity of 4      
      Vector vec = new Vector(4);

      // use add() method to add elements in the vector
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(1);

      // set new size to 8
      vec.setSize(8);
      
      // let us print all the elements available in vector
      System.out.println("Added numbers are :- "); 
      for (Integer number : vec) {         
         System.out.println("Number = " + number);
      }           
   }    
} 

Let us compile and run the above program, this will produce the following result.

Added numbers are :- 
Number = 4
Number = 3
Number = 2
Number = 1
Number = null
Number = null
Number = null
Number = null



Advertisements
Advertisements