# Set the size of a Vector in Java

Java 8Object Oriented ProgrammingProgramming

The java.util.Vector.setSize() method can be used to set the size of a Vector in Java. If the new size that is set is greater than the old size of the Vector, then null values are added to the positions created. If the new size that is set is lesser than the old size of the Vector, then the elements at positions more than the new size are discarded.

A program that demonstrates this is given as follows:

## Example

Live Demo

import java.util.Vector;
public class Demo {
public static void main(String args[]) {
Vector vec = new Vector();
System.out.println("The Vector elements are: " + vec);
vec.setSize(5);
System.out.println("The Vector elements are: " + vec);
}
}

The output of the above program is as follows:

The Vector elements are: [4, 1, 7, 3, 5, 9, 2, 8, 6]
The Vector elements are: [4, 1, 7, 3, 5]

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. The Vector is displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector();
System.out.println("The Vector elements are: " + vec);
vec.setSize(5);
System.out.println("The Vector elements are: " + vec);