Write a Java program to get the Index of the first occurrence of the specified item in Vector collection


The code you provided demonstrates how to find the index of the first occurrence of an item in a Vector using the indexOf method in Java. Here's a breakdown of what the code does:

  • A Vector<String> object named vec_list is created.
  • Elements "Apple", "Grapes", "Banana", "Mango", "Cherry", and "Orange" are added to vec_list using the add method.
  • The indexOf method is used to find the index of the first occurrence of the item "Papaya" in vec_list. The index is printed using System.out.println.
  • Similarly, the indexOf method is used to find the index of the first occurrence of the item "Grapes" in vec_list. The index is printed using System.out.println.

As you can see, the indexOf method returns -1 for the item "Papaya" since it does not exist in the vector. However, it returns 1 for the item "Grapes" since it is found at index 1 in the vec_list vector.

Source Code

import java.util.*;
public class First_Occurrence
{
	public static void main(String[] args)
	{
		Vector < String > vec_list = new Vector < String > ();
		vec_list.add("Apple");
		vec_list.add("Grapes");
		vec_list.add("Banana");
		vec_list.add("Mango");
		vec_list.add("Cherry");
		vec_list.add("Orange");
		System.out.println("Index of First Occurrence of item 'Papaya' is : " + vec_list.indexOf("Papaya"));
		System.out.println("Index of First Occurrence of item 'Grapes' is : " + vec_list.indexOf("Grapes"));
	}
}

Output

Index of First Occurrence of item 'Papaya' is : -1
Index of First Occurrence of item 'Grapes' is : 1

Example Programs