The
Vector
class is a growable array of objects. The elements ofVector
can be accessed using an integer index. Also, the size of aVector
can be increased or decreased. Read more aboutVector
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:
public int indexOf(Object obj, int index);
The method takes two arguments.
obj
: The element to be searched.
index
: The index after which the element is to be searched.
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.
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));}}
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.