Write a Java program to change the size of a Vector collection


The code you provided is written in Java and demonstrates the use of the Vector class to manipulate a list of integers. Here's a breakdown of what the code does:

  • It imports the necessary java.util package, which contains the Vector class and other utility classes.
  • It declares a class named ChangeSize.
  • Within the ChangeSize class, the main method is defined, which serves as the entry point for the program.
  • Inside the main method, a Vector<Integer> named vec_list is declared and initialized. This vector is used to store a list of integers.
  • The add method is called on the vec_list object multiple times to add integers to the vector.
  • The System.out.println statement is used to print the vector elements to the console.
  • The setSize method is called on the vec_list object, specifying a new size of 10 for the vector. If the new size is greater than the current size, additional elements are added to the vector with a default value of zero. If the new size is smaller, the vector is truncated to the specified size.
  • Another System.out.println statement is used to print the modified vector elements to the console.

Source Code

import java.util.*;
public class ChangeSize
{
	public static void main(String[] args)
	{
		Vector < Integer > vec_list = new Vector < Integer > ();
		vec_list.add(10);
		vec_list.add(20);
		vec_list.add(30);
		vec_list.add(40);
		vec_list.add(50);
 
		System.out.println("Vector Elements : " + vec_list);
 
		vec_list.setSize(10);
 
		System.out.println("Vector Elements : " + vec_list);
	}
}

Output

Vector Elements : [10, 20, 30, 40, 50]
Vector Elements : [10, 20, 30, 40, 50, null, null, null, null, null]

Example Programs