Vector

Set Vector size example

With this example we are going to demonstrate how to set the Vector size, that is setting a greater or less size than the current size of the Vector. In short, to set the Vector size you should:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Invoke the setSize(int newSize) API method of Vector. If the newSize is less than the current size of the Vector elements after newSize index are discarded. If the newSize is greater than the current size of Vector, null values are added at the end of the Vector.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
 
public class SetVectorSizeExample {
 
  public static void main(String[] args) {

    // Create a Vector and populate it with elements
    Vector vector = new Vector();
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
    vector.add("element_2");
 
    /*

void setSize(int newSize) sets the size of the Vector. If the newSize is less 

than the current size of the Vector elements after newSize index are discarded. 

If the newSize is grater than the current size of Vector, null values are added 

at the end of the Vector.
    */
    vector.setSize(3);
 
    System.out.println("Vector(" + vector.size() + ") contains elements : " + vector);
 
    vector.setSize(5);
 
    System.out.println("Vector(" + vector.size() + ") contains elements : " + vector);
 
  } 
}

Output:

Vector(3) contains elements : [element_1, element_2, element_3]
Vector(5) contains elements : [element_1, element_2, element_3, null, null]

 
This was an example of how to set the Vector size in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button