Skip to Content

Search an element of Java Vector Example

  1. /*
  2.   Search an element of Java Vector Example
  3.   This Java Example shows how to search an element of java Vector object using
  4.   contains, indexOf and lastIndexOf methods.
  5. */
  6.  
  7. import java.util.Vector;
  8.  
  9. public class SearchAnElementInVectorExample {
  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 check whether the specified element exists in Java Vector use
  27.       boolean contains(Object element) method.
  28.       It returns true if the Vector contains the specified objct, false
  29.       otherwise.
  30.     */
  31.    
  32.     boolean blnFound = v.contains("3");
  33.     System.out.println("Does Vector contain 3 ? " + blnFound);
  34.  
  35.     /*
  36.       To get an index of specified element in Vector use
  37.       int indexOf(Object element) method.
  38.       This method returns the index of the specified element in Vector.
  39.       It returns -1 if not found.
  40.     */
  41.  
  42.     int index = v.indexOf("5");
  43.     if(index == -1)
  44.       System.out.println("Vector does not contain 5");
  45.     else
  46.       System.out.println("Vector contains 5 at index :" + index);
  47.      
  48.     /*
  49.       To get last index of specified element in Vector use
  50.       int lastIndexOf(Object element) method.
  51.       This method returns index of the last occurrence of the
  52.       specified element in Vector. It returns -1 if not found.
  53.     */
  54.  
  55.     int lastIndex = v.lastIndexOf("2");
  56.     if(lastIndex == -1)
  57.       System.out.println("Vector does not contain 2");
  58.     else
  59.       System.out.println("Last occurrence of 2 in Vector is at index :" + lastIndex);
  60.      
  61.   }  
  62. }
  63. /*
  64. Output would be
  65. Does Vector contain 3 ? true
  66. Vector contains 5 at index :4
  67. Last occurrence of 2 in Vector is at index :6
  68. */