What is the Vector.indexOf 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 Vector here.

The indexOf method of the Vector class can be used to get the index of the first occurrence of the specified element in the Vector object.

Syntax

public int indexOf(Object obj);

Parameter

  • obj: The element to be searched in the Vector is passed as an argument.

Return value

This method returns the first index at which the specified element is present in the Vector.

If the element is not present in the Vector, then -1 is returned.

Code

The code below demonstrates how to use the indexOf method.

import java.util.Vector;
class IndexOfExample {
public static void main( String args[] ) {
Vector<String> vector = new Vector<>();
vector.add("1");
vector.add("2");
vector.add("1");
System.out.println("The vector is " + vector);
System.out.println("First Index of element '1' is : " + vector.indexOf("1"));
System.out.println("First Index of element '2' is : " + vector.indexOf("2"));
System.out.println("First Index of element '3' is : " + vector.indexOf("3"));
}
}

Explanation

In the above code:

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

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

  • From line number 5 to 7, we use the add method of the vector object to add three elements ("1","2","3") to the vector.

  • In line number 10, we use the indexOf method of the vector object to get the index of the first occurrence of the element "1". The element "1" is present at two indices: 0 and 2. We get 0 as a result since that is the first occurrence.

  • In line number 11, we use the indexOf method of the vector object to get the index of the first occurrence of the element "2". The element "2" is present only at index 1, so it is returned.

  • In line number 12, we use the indexOf method of the vector object to get the index of the first occurrence of the element "3". The element "3" is not present in the vector, so -1 is returned.

Free Resources