What is the Vector.indexOf method in Java?
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index and the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
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 theVectoris 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
Vectorclass. -
In line number 4, we create a new object for the
Vectorobject with the namevector. -
From line number 5 to 7, we use the
addmethod of thevectorobject to add three elements ("1","2","3") to thevector. -
In line number 10, we use the
indexOfmethod of thevectorobject to get the index of the first occurrence of the element"1". The element"1"is present at two indices:0and2. We get0as a result since that is the first occurrence. -
In line number 11, we use the
indexOfmethod of thevectorobject to get the index of the first occurrence of the element"2". The element"2"is present only at index1, so it is returned. -
In line number 12, we use the
indexOfmethod of thevectorobject to get the index of the first occurrence of the element"3". The element"3"is not present in thevector, so-1is returned.