Search an element of Vector in Java

Java 8Object Oriented ProgrammingProgramming

An element of a Vector can be searched using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the Vector, then this method returns -1.

A program that demonstrates this is given as follows:

Example

 Live Demo

import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector(5);
      vec.add(4);
      vec.add(1);
      vec.add(7);
      vec.add(9);
      vec.add(2);
      vec.add(8);
      System.out.println("The Vector elements are: " + vec);
      System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9));
      System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5));
   }
}

The output of the above program is as follows:

The Vector elements are: [4, 1, 7, 9, 2, 8]
The index of element 9 in Vector is: 3
The index of element 5 in Vector is: -1

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. Vector.indexOf() returns the index of the first occurrence of elements 9 and 5 and that is displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector(5);
vec.add(4);
vec.add(1);
vec.add(7);
vec.add(9);
vec.add(2);
vec.add(8);
System.out.println("The Vector elements are: " + vec);
System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9));
System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5));
raja
Published on 07-Feb-2019 16:07:17
Advertisements