What is the Vector.lastIndexOf() method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about the Vector class here.

The lastIndexOf method of the Vector class will search for the specific element backwards from the specific index and return the first index at which the searching element is found.

Syntax

public int lastIndexOf(Object obj, int index);

Parameters

This method takes 2 arguments.

  1. obj: The element to be searched.

  2. index: The index from which the element is to be searched backwards.

Return value

When searching for the passed element backwards from the specific index, the first index at which the searching element is found is returned.

If the element is not present from the specified index, then -1 is returned.

Code

import java.util.Vector;
class LastIndexOfExample {
public static void main( String args[] ) {
Vector<String> vector = new Vector<>();
vector.add("one");
vector.add("two");
vector.add("two");
vector.add("three");
System.out.println("The vector is " + vector);
System.out.println("Last Index of element 'two' from index 3 : " + vector.lastIndexOf("two", 3));
System.out.println("Last Index of element 'four' from index 3 : " + vector.lastIndexOf("four", 3));
}
}

Explanation

  • In line number 1, we import the Vector class.

  • In line number 4, we create a new Vector object with the name vector.

  • From line numbers 5 to 8, we use the add method of the vector object to add four elements ("one","two", "two", "three") to the vector.

  • In line number 11, we use the lastIndexOf method of the vector object with the searching element as two and 3 as the index. This method will search backwards for the element two from index 3. The element two is present in two indices: 1 and 2. We get 2 as a result since that is the first occurrence from index 3 when searching backwards.

  • In line number 12, we use the lastIndexOf method of the vector object with the searching element as four and 3 as the index. This method will search backwards for the element two from index 3. The element four is not present in the vector, so -1 is returned.

Free Resources