What is the Vector.indexOf (element, index) method in Java?

Vector class in Java

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

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

Syntax

public int indexOf(Object obj, int index);

Parameter

The method takes two arguments.

  1. obj: The element to be searched.

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

Return value

The function returns the index of the first occurrence of the passed element at or after the passed index.

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

Code

The code below demonstrates the use of the indexOf method:

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

Explanation

In the code above, we took the following steps:

  • In line 1, we import the Vector class.

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

  • From lines 5 to 8, we call the add method of the vector object to add four elements ("one","one", "one", "two") to the vector.

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

  • In line 11, we use the indexOf method of the vector object to get the index of the first occurrence of the element "one" from index 3. From index 3, the element "one" is not present, so -1 will be returned.

Free Resources