# Set the size of a Vector in Java

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();
vec.add(4);
vec.add(1);
vec.add(7);
vec.add(3);
vec.add(5);
vec.add(9);
vec.add(2);
vec.add(8);
vec.add(6);
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();
vec.add(4);
vec.add(1);
vec.add(7);
vec.add(3);
vec.add(5);
vec.add(9);
vec.add(2);
vec.add(8);
vec.add(6);
System.out.println("The Vector elements are: " + vec);

The Vector.setSize() method is used to set the size of the Vector to 5. The Vector is displayed again with only 5 elements as the rest of the elements are discarded. A code snippet which demonstrates this is as follows:

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

Advertisements