Java Utility Library

Java Vector - setSize() Method



The java.util.Vector.setSize() method is used to set the size of the 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.

Syntax

public void setSize(int newSize)

Parameters

newSize Specify new size of the vector.

Return Value

void type.

Exception

Throws ArrayIndexOutOfBoundsException, if the new size is negative.

Example:

In the example below, the java.util.Vector.setSize() method is used to set the size of the vector called MyVector.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVector = new Vector<Integer>();

    //populating vector
    MyVector.add(10);
    MyVector.add(20);
    MyVector.add(30);
    MyVector.add(40);
    MyVector.add(50);

    System.out.println("MyVector contains: " + MyVector);
    MyVector.setSize(3);
    System.out.println("MyVector contains: " + MyVector);    
    MyVector.setSize(5);
    System.out.println("MyVector contains: " + MyVector);  
  }
}

The output of the above code will be:

MyVector contains: [10, 20, 30, 40, 50]
MyVector contains: [10, 20, 30]
MyVector contains: [10, 20, 30, null, null]

❮ Java.util - Vector