Write a Java program to remove the first occurrence of the specified element from Vector collection


The code you provided demonstrates how to remove the first occurrence of an element from a Vector using the removeElement method in Java. Here's a breakdown of what the code does:

  • A Vector<String> object named vec_list is created.
  • Elements "Red", "Green", "Blue", "Yellow", and "Orange" are added to vec_list using the add method.
  • The initial contents of vec_list are printed using System.out.println.
  • The removeElement method is called on vec_list, passing "Red" as an argument. This removes the first occurrence of "Red" from the vector.
  • The updated contents of vec_list are printed using System.out.println.

As you can see, after calling vec_list.removeElement("Red"), the first occurrence of "Red" is removed from vec_list. The resulting vec_list contains the remaining elements.

Source Code

import java.util.*;
public class Remove_FirstOccurrence
{
	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.removeElement("Red");
		System.out.println("Vector elements: " + vec_list);
	}
}

Output

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

Example Programs