What is the Vector.setSize method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

The setSize method will change the size of the Vector object.

Syntax

public void setSize(int newSize)

Parameters

This method takes the new size of the Vector object as an argument.

  • If the size is greater than the current vector size, then null elements are added in the new places.
  • If the size is lesser than the current vector size, then all the elements at the index size and above are removed from the vector.

Return value

This method doesn’t return any values.

Code

import java.util.Vector;
import java.util.ArrayList;
class SetSize {
public static void main( String args[] ) {
Vector<Integer> vector = new Vector<>();
vector.add(1);
vector.add(2);
vector.add(3);
vector.add(4);
System.out.println("The vector is "+ vector);
System.out.println("The size is "+ vector.size());
vector.setSize(2);
System.out.println("\nThe vector is "+ vector);
System.out.println("The size is "+ vector.size());
vector.setSize(4);
System.out.println("\nThe vector is "+ vector);
System.out.println("The size is "+ vector.size());
}
}

In the code above,

  • In line number 1 : We import the Vector class.

  • From line numbers 5 to 9: We create a new Vector object with the name vector and add four elements (1,2,3,4) to the vector object using the add method. Now the size of the vector is 4.

  • In line number 14: We use the setSize method to change the size of the vector object from 4 to 2. The elements present in index 2 and after are removed from the vector and the size becomes 2.

  • In line number 19: We use the setSize method to change the size of the vector object from 2 to 4. There are already 2 elements present in the vector. For the new 2 positions, null is inserted.

Free Resources