Home » Core Java » util » Vector » Set Vector size example

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of