Skip to Content

Search an element of Java Vector from specific index Example

  1. /*
  2.   Search an element of Java Vector from specific index Example
  3.   This Java Example shows how to search an element of java Vector from specific
  4.   index using indexOf and lastIndexOf methods.
  5. */
  6.  
  7. import java.util.Vector;
  8.  
  9. public class SearchAnElementFromSpecificIndexVectorExample {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create a Vector object
  14.     Vector v = new Vector();
  15.    
  16.     //Add elements to Vector
  17.     v.add("1");
  18.     v.add("2");
  19.     v.add("3");
  20.     v.add("4");
  21.     v.add("5");
  22.     v.add("1");
  23.     v.add("2");
  24.  
  25.     /*
  26.       To search an index of specified element in Vector from specified index use
  27.       int indexOf(Object element, int startIndex) method.
  28.       This method returns the index of the first occurence of the specified
  29.       element after startIndex in Vector. It returns -1 if not found.
  30.     */
  31.  
  32.     int index = v.indexOf("1",4);
  33.     if(index == -1)
  34.       System.out.println("Vector does not contain 1 after index # 4");
  35.     else
  36.       System.out.println("Vector contains 1 after index # 4 at index #" + index);
  37.      
  38.     /*
  39.       To get last index of specified element after specified index in Vector use
  40.       int lastIndexOf(Object element, int startIndex) method.
  41.       This method returns index of the last occurrence of the
  42.       specified element after startIndex in Vector. It returns -1 if not found.
  43.     */
  44.  
  45.     int lastIndex = v.lastIndexOf("2" , 5);
  46.     if(lastIndex == -1)
  47.       System.out.println("Vector does not contain 2 after index # 5");
  48.     else
  49.       System.out.println("Last occurrence of 2  after index # 5 in Vector
  50.                                               is at index #" + lastIndex);
  51.      
  52.   }  
  53. }
  54. /*
  55. Output would be
  56. Vector contains 1 after index # 4 at index #5
  57. Last occurrence of 2  after index # 5 in Vector is at index #1
  58. */