Write a Java program to remove an element from Vector collection based on the specified index


The code is written in Java and demonstrates the usage of the Vector class to remove an element from a vector. Let's go through the code step by step:

  • The code starts with the import statement, which includes the required packages for the code to run successfully.
  • The class "RemoveElement" is defined, which serves as the main class for our program.
  • Inside the main method, a Vector object called "vec_list" is created using the Vector class. The Vector class is similar to an ArrayList and provides methods to manipulate and access elements in a dynamic array.
  • Several strings are added to the vector using the add method. These strings are "Red", "Green", "Blue", "Yellow", and "Orange".
  • The line System.out.println("Vector Elements : " + vec_list); prints the elements of the vector to the console, displaying all the strings added to the vector.
  • The line vec_list.removeElementAt(0); removes the element at index 0 from the vector. In this case, it removes the string "Red" from the vector.
  • Finally, the line System.out.println("Vector Elements : " + vec_list); is executed again to print the updated elements of the vector to the console. After removing the element at index 0, the vector now contains "Green", "Blue", "Yellow", and "Orange".

Source Code

import java.util.*;
public class RemoveElement
{
	public static void main(String[] args)
	{
		Vector < String > vec_list = new Vector < String > ();
		vec_list.add("Red");
		vec_list.add("Green");
		vec_list.add("Blue");
		vec_list.add("Yellow");
		vec_list.add("Orange");
 
		System.out.println("Vector Elements : " + vec_list);
 
		vec_list.removeElementAt(0);
 
		System.out.println("Vector Elements : " + vec_list);
	}
}

Output

Vector Elements : [Red, Green, Blue, Yellow, Orange]
Vector Elements : [Green, Blue, Yellow, Orange]

Example Programs