How to Set Size of Java Vector


In this example we will show how to set the size of Vector object with setSize method in Java. Size of the Vector can be changed anytime after creating it with this method.

Source Code

package com.beginner.examples;

import java.util.Vector;

public class SetSizeOfJavaVector {

	public static void main(String[] args) {
		
	    //create Vector. 
	    Vector vector = new Vector();
	    
	    vector.add("A");
	    vector.add("B");
	    vector.add("C");
	    vector.add("D");
	    
	    System.out.println("Before setting size, vector contains :");
	    for(int index=0; index < vector.size(); index++) {
	    	System.out.println(vector.get(index));
	    }
	    
	    /*
	     *  To set the size of Vector use setSize(int newSize) method.
	     */
	    vector.setSize(3);
	    
	    System.out.println("After setting size, vector contains :");
	    for(int index=0; index < vector.size(); index++) {
	    	System.out.println(vector.get(index));
	    }
	      
	}

}

Output:

Before setting size, vector contains :
A
B
C
D
After setting size, vector contains :
A
B
C

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments