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


The code you provided demonstrates how to find the index of the last occurrence of an item in a Vector using the lastIndexOf 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", "Papaya", "Cherry", and "Orange" are added to vec_list using the add method.
  • The lastIndexOf method is used to find the index of the last occurrence of the item "Grapes" in vec_list. The index is printed using System.out.println.
  • Similarly, the lastIndexOf method is used to find the index of the last occurrence of the item "Mango" in vec_list. The index is printed using System.out.println.

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

Source Code

import java.util.*;
public class Last_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("Papaya");
		vec_list.add("Cherry");
		vec_list.add("Orange");
 
		System.out.println("Index of Last Occurrence of item 'Grapes' is : " + vec_list.lastIndexOf("Grapes"));
		System.out.println("Index of Last Occurrence of item 'Mango' is : " + vec_list.lastIndexOf("Mango"));
	}
}

Output

Index of Last Occurrence of item 'Grapes' is : 1
Index of Last Occurrence of item 'Mango' is : -1

Example Programs