indexOf(Object, int) : This method is available in java.util.Vector class of Java.
Syntax:
int java.util.Vector.indexOf(Object o, int index)
This method takes two arguments. This method returns the index of the first occurrence of the specified element in this vector, searching forwards from the index or returns -1 if the element is not found.
Parameters: Two parameters are required for this method.
o: the element to search for index.
index: to start searching from.
Returns: the index of the first occurrence of the element in this vector at position index or later in the vector; -1 if the element is not found.
Throws:
IndexOutOfBoundsException - if the specified index is negative.
Approach 1: When no exception
Java
import java.util.Vector;public class VectorindexOf2 {public static void main(String[] args) {Vector<String> vector = new Vector<>();vector.add("Hello");vector.add("Java");vector.add("C++");vector.add("Program");int index = 1;Object o = "Hello";System.out.println(vector.indexOf(o, index));}}
Output:
-1
Approach 2: IndexOutOfBoundsException
Java
import java.util.Vector;public class VectorindexOf2 {public static void main(String[] args) {Vector<String> vector = new Vector<>();vector.add("Hello");vector.add("Java");vector.add("C++");vector.add("Program");int index = -1;Object o = "Hello";System.out.println(vector.indexOf(o, index));}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10 at java.base/java.util.Vector.indexOf(Vector.java:400)
No comments:
Post a Comment