How to change the size of a Vector in Java - setSize()
You can manipulate the size of Vector using the setSize() of the Vector class. If the new size is larger than the current size then, all items that fall after the index of the current size have a value null. If the new size is smaller than the current size then, all items that are after the index of the current size are removed from Vector.
The example below implements both cases. Initially, we have a Vector of 7 elements. We set the size to 10 so, 3 null elements will be inserted at the end of Vector.
In the second part of the code, we set the size of Vector to 5 so, the last 5 elements will be deleted by Vector including null.
The example below implements both cases. Initially, we have a Vector of 7 elements. We set the size to 10 so, 3 null elements will be inserted at the end of Vector.
In the second part of the code, we set the size of Vector to 5 so, the last 5 elements will be deleted by Vector including null.
import java.util.Vector;Runtime:
public class setSize {
public static void main(String[] args) {
Vector< String> vec = new Vector< String> ();
//insert elements
vec.add("e1");
vec.add("e2");
vec.add("e3");
vec.add("e4");
vec.add("e5");
vec.add("e6");
vec.add("e7");
//change the size of Vector to 10
vec.setSize(10);
System.out.println("Vector size: "+vec.size());
System.out.println("Vector Elements:");
for(String vec)
System.out.println(e);
//the size of Vector is smaller than the current size
vec.setSize(5);
System.out.println("\nVector tail: "+vec.size());
System.out.println("Vector Elements:");
for(String vec)
System.out.println(e);
}
}
Vector Size: 10
Vector Elements:
e1
e2
e3
e4
e5
e6
e7
null
null< br />null
Vector size: 5
Vector elements:
e1
e2
e3
e4
e5