public
synchronized int indexOf(Object o, int index)
Returns
the index of the first occurrence of the specified element in this
vector, searching forwards from index, or returns -1 if the element
is not found.
import java.util.*; class VectorIndexOf1{ public static void main(String args[]){ Vector<Integer> myVector; myVector = new Vector<> (); /*Add Elements to myVector*/ myVector.add(10); myVector.add(11); myVector.add(12); myVector.add(10); myVector.add(12); System.out.println("Elements in myVector"); System.out.println(myVector); System.out.print("\nIndex of 12 is "); System.out.println(myVector.indexOf(12,2)); System.out.print("\nIndex of 10 is "); System.out.println(myVector.indexOf(10,1)); System.out.print("\nIndex of 11 is "); System.out.println(myVector.indexOf(11,2)); } }
Output
Elements in myVector [10, 11, 12, 10, 12] Index of 12 is 2 Index of 10 is 3 Index of 11 is -1
1. Throws IndexOutOfBoundsException if the specified index is negative
import java.util.*; class VectorIndexOfIndexOut{ public static void main(String args[]){ Vector<Integer> myVector; myVector = new Vector<> (); /*Add Elements to myVector*/ myVector.add(10); myVector.add(11); myVector.add(12); myVector.add(10); myVector.add(12); System.out.println("Elements in myVector"); System.out.println(myVector); System.out.print("\nIndex of 12 is "); System.out.println(myVector.indexOf(12,-1)); } }
Output
Elements in myVector [10, 11, 12, 10, 12] Index of 12 is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Vector.indexOf(Vector.java:404) at VectorIndexOfIndexOut.main(VectorIndexOfIndexOut.java:19)
No comments:
Post a Comment