Write a Java program to count the items of a Vector collection


The code you provided is written in Java and demonstrates how to use a Vector to store a collection of integers and count the number of elements in the Vector. Here's an explanation of the code:

  • import java.util.*;: This line imports the java.util package, which contains the Vector class and other utility classes.
  • public class Count_Items: This line declares a public class named Count_Items.
  • public static void main(String[] args): This is the main method where the execution of the program starts. It takes an array of strings as command line arguments.
  • Vector<Integer> vec_list = new Vector<Integer>();: This line declares and initializes a Vector object named vec_list that can store Integer values. Note that using generics (<Integer>) is not necessary in newer versions of Java.
  • for (int i = 1; i <= 10; i++): This line starts a for loop with the loop variable i initialized to 1, and it continues as long as i is less than or equal to 10. After each iteration, i is incremented by 1.
  • vec_list.add(i);: Inside the for loop, this line adds the value of i to the vector vec_list.
  • System.out.println("Size of vector collection :" + vec_list.size());: This line prints the size of the vector collection by concatenating the string "Size of vector collection :" with the size of the vector using the size() method. The size() method returns the number of elements in the vector.

Source Code

import java.util.*;
public class Count_Items
{
	public static void main(String[] args)
	{
		Vector <Integer> vec_list = new Vector <Integer>();
 
		for (int i = 1; i <= 10; i++)
		{
			vec_list.add(i);
		}
		System.out.println("Size of vector collection :" + vec_list.size());
 
	}
}

Output

Size of vector collection :10

Example Programs