Thursday 8 May 2014

Vector : lastIndexOf (Object o, int index)

public synchronized int lastIndexOf(Object o, int index)
Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found.

import java.util.*;

class VectorLastIndexOf1{
 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("\nLast Index of 12 from 3 is ");
  System.out.println(myVector.lastIndexOf(12, 3));
  System.out.print("\nLast Index of 100 from 4 is ");
  System.out.println(myVector.lastIndexOf(100, 4));
 }
}

Output
Elements in myVector
[10, 11, 12, 10, 12]

Last Index of 12 from 3 is 2

Last Index of 100 from 4 is -1

1. Throws IndexOutOfBoundsException if the specified index is greater
than or equal to the current size of this vector

import java.util.*;

class VectorLastIndexOf1IndeOut{
 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("\nLast Index of 12 from 5 is ");
  System.out.println(myVector.lastIndexOf(12, 5));
 }
}

Output
Elements in myVector
[10, 11, 12, 10, 12]

Last Index of 12 from 5 is Exception in thread "main" java.lang.IndexOutOfBounds
Exception: 5 >= 5
        at java.util.Vector.lastIndexOf(Vector.java:443)
        at VectorLastIndexOf1IndeOut.main(VectorLastIndexOf1IndeOut.java:19)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment