Java Utility Library

Java Vector - indexOf() Method



The java.util.Vector.indexOf() method returns index of the first occurrence of the specified element in the vector, searching forward from specified index. It returns -1 if element is not present in the vector.

Syntax

public int indexOf(Object obj, int index)

Parameters

obj Specify the element to search for in the vector.
index Specify index to search searching from.

Return Value

Returns the index of the first occurrence of the specified element in the vector, searching forward from specified index, or -1 if element is not present in the vector.

Exception

NA.

Example:

In the example below, the java.util.Vector.indexOf() method is used to find the index of first occurrence of the specified element in the vector MyVector, searching forward from specified index.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVector = new Vector<Integer>();

    //populating vector
    MyVector.add(10);
    MyVector.add(30);
    MyVector.add(20);
    MyVector.add(50);
    MyVector.add(30);

    System.out.print("30 appeared first time after index=2 at index="); 
    System.out.print(MyVector.indexOf(30, 2));
  }
}

The output of the above code will be:

30 appeared first time after index=2 at index=4

❮ Java.util - Vector