Java Vector indexOf(Object o) Example

The elementAt(int index) and get(int index) method of java.util.Vector class will get you the element at the specified index whereas indexOf(Object o) method will get you the index of the first occurrence of the specified element in the vector

Signature

public int indexOf(Object o) 

This method returns the index of the first occurrence of the specified element in the vector, or -1 if the vector does not contain the specified element.

Example

The following example shows the usage of java.util.Vector.indexOf(o) method.

import java.util.Vector;

public class IndexOfMethodVectorExample 
{
    public static void main(String args[])
    {
     // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        
        //Lets get the index of Element2
        System.out.println("Index of \"Element2\" is : "+vector1.indexOf("Element2"));
    }
}

Output

Index of "Element2 is : 1

Leave a Reply

Your email address will not be published. Required fields are marked *