What is the Vector.setSize method in Java?
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index and the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
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
sizeis greater than the current vector size, then null elements are added in the new places. - If the
sizeis 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
Vectorclass. -
From line numbers 5 to 9: We create a new
Vectorobject with the namevectorand add four elements (1,2,3,4) to thevectorobject using theaddmethod. Now the size of thevectoris4. -
In line number 14: We use the
setSizemethod to change the size of thevectorobject from4to2. The elements present in index2and after are removed from the vector and thesizebecomes2. -
In line number 19: We use the
setSizemethod to change the size of thevectorobject from2to4. There are already 2 elements present in thevector. For the new 2 positions,nullis inserted.