What is the Vector.indexOf (element, index) method in Java?
Vector class in Java
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index. Also, the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
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.
-
obj: The element to be searched. -
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
Vectorclass. -
In line 4, we create a new object for the
Vectorobject with the namevector. -
From lines 5 to 8, we call the
addmethod of thevectorobject to add four elements ("one","one", "one", "two") to thevector. -
In line 10, we use the
indexOfmethod of thevectorobject to get the index of the first occurrence of the element"one"from index1. From index1, the element"one"is present at two indices:1and2. We will get1as a result since that is the first occurrence from index1. -
In line 11, we use the
indexOfmethod of thevectorobject to get the index of the first occurrence of the element"one"from index3. From index3, the element"one"is not present, so-1will be returned.