Vector setsize: In the previous article, we have discussed about Java Vector ensureCapacity( ) Method with Example
In this article, we are going to see the use of Java Vector setSize() method along with examples.
Java Vector setSize( ) Method with Example
This java.util.Vector.setSize()
method sets the size of the vector and any empty element index is assigned null value. Its return type is void.
Syntax:
vectorName.setSize(int new_size );
Where,
vectorName
refers to the name of the vector.new_size
refers to the parameter passed to method which sets the new size of the vector.
Approach:
- Create a vector of string data type and add some elements to it.
- Print the elements.
- Now, set the vector size to 9 by passing it into the
setSize( )
method. - Print the vector elements and its size after setting the new size.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a Vector of string datatype Vector<String> vec = new Vector<String>(); // Adding some elements to the vector vec.add("One"); vec.add("Two"); vec.add("Three"); vec.add("Four"); vec.add("Five"); vec.add("Six"); vec.add("Seven"); // Prints the vector elements System.out.println("The vector elements are "+vec); // Sets the size of the vector vec.setSize(9); // Prints the vector elements after set the size of the vector System.out.println("The vector elements after set the size are "+vec); // Prints the size of the vector System.out.println("The size of the vector after setting size to 9 is "+vec.size()); } }
Output: The vector elements are [One, Two, Three, Four, Five, Six, Seven] The vector elements after set the size are [One, Two, Three, Four, Five, Six, Seven, null, null] The size of the vector after setting size to 9 is 9
Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.
Related Java Programs: