Home »
Java programming language
Java Vector indexOf() Method with Example
Vector Class indexOf() method: Here, we are going to learn about the indexOf() method of Vector Class with its syntax and example.
Submitted by Preeti Jain, on March 17, 2020
Vector Class indexOf() method
Syntax:
public int indexOf(Object ob);
public int indexOf(Object ob, int indices);
- indexOf() method is available in java.util package.
- indexOf(Object ob) method is used to return the index of the first occurrence of the given element.
- indexOf(Object ob, int indices) method is used to find the index of the first occurrence of the given object in this Vector and searching starts at the given indices.
- These methods may throw an exception at the time of returning an index.
IndexOutOfBoundsException: This exception may throw when the given parameter is not in a range (indices<0).
- These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.
Parameter(s):
- In the first case, indexOf(Object ob),
Object ob – represents the object for which index to be returned.
-
In the first case, indexOf(Object ob, int indices),
- Object ob – represents the index of searching starts.
- int indices – represents the object for which index to be returned.
Return value:
In both the cases, the return type of the method is int,
- In the first case, it gets the index of the first occurrence of the given object when it exists otherwise it returns -1.
- In the second case, it returns the index of the first occurrence of the given object when exists.
Example:
// Java program to demonstrate the example
// of indexOf() method of Vector
import java.util.*;
public class IndexOfVector {
public static void main(String[] args) {
// Instantiates a vector object
Vector < String > v = new Vector < String > (10);
// By using add() method is to add
// the elements in vector
v.add("C");
v.add("C++");
v.add("SFDC");
v.add("JAVA");
v.add("C++");
//Display Vector
System.out.println("v: " + v);
// By using indexOf(object) method is used
// to return the index of first occurrence of the
// given object
System.out.println("v.indexOf(C++): " + v.indexOf("C++"));
// By using indexOf(object, indices) method is used
// to return the index of first occurrence of the
// given object and searching starts from the
// given indices
System.out.println("v.indexOf(C++,2): " + v.indexOf("C++", 2));
}
}
Output
v: [C, C++, SFDC, JAVA, C++]
v.indexOf(C++): 1
v.indexOf(C++,2): 4