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. It returns -1 if element is not present in the vector.

Syntax

public int indexOf(Object obj)

Parameters

obj Specify the element to search for in the vector.

Return Value

Returns the index of the first occurrence of the specified element in the vector, 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.

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 at index=" + MyVector.indexOf(30)); 
  }
}

The output of the above code will be:

30 appeared first time at index=1

❮ Java.util - Vector