Java Vector setSize(int newSize) Method Example

The setSize(int newSize) method of java.util.Vector class will sets 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 will be discarded.

Signature

public void setSize(int newSize)

This method sets the size of the vector and will throw java.lang.ArrayIndexOutOfBoundsException if the new size is negative.

Example

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

import java.util.Vector;

public class SetSizeMethodVectorExample 
{
    public static void main(String args[])
    {
     // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        vector1.add("Element4");
        
        //Set the size of the vector
        vector1.setSize(8);
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector1**");
        for(String temp:vector1)
        {
            System.out.println(temp);
        }
        
        //Lets again set the size of the vector
        vector1.setSize(2);
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector1**");
        for(String temp:vector1)
        {
            System.out.println(temp);
        }
    }
}

Output

**Elements of the Vector1**
Element1
Element2
Element3
Element4
null
null
null
null
**Elements of the Vector1**
Element1
Element2

Leave a Reply

Your email address will not be published. Required fields are marked *