Write a Java program to remove all elements of Vector collection
The code you provided is written in Java and demonstrates how to remove all elements from a Vector using the clear() method. 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 Remove: This line declares a public class named Remove.
- 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("Before Remove Vector Elements : " + vec_list); : This line prints the elements of the vector before removing them by concatenating the string "Before Remove Vector Elements :" with the vector vec_list. The println function automatically converts the vector to a string representation.
- vec_list.clear();: This line removes all elements from the vector by calling the clear() method. After this call, the vector will be empty.
- System.out.println("After Remove Vector Elements : " + vec_list); : This line prints the elements of the vector after removing them. Since all elements have been cleared, the vector will be empty.
Source Code
import java.util.*;
public class Remove
{
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("Before Remove Vector Elements : " + vec_list);
vec_list.clear();
System.out.println("After Remove Vector Elements : " + vec_list);
}
}
Output
Before Remove Vector Elements : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After Remove Vector Elements : []