The
Vector
class is a growable array of objects. The elements ofVector
can be accessed using an integer index and the size of aVector
can be increased or decreased. Read more aboutVector
here.
The setSize
method will change the size of the Vector
object.
public void setSize(int newSize)
This method takes the new size of the Vector
object as an argument.
size
is greater than the current vector size, then null elements are added in the new places.size
is lesser than the current vector size, then all the elements at the index size and above are removed from the vector.This method doesn’t return any values.
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.